<html><head>
      <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
   <title>JAXB Users Guide</title><link rel="stylesheet" href="style/documentation.css" type="text/css"><meta name="generator" content="DocBook XSL-NS Stylesheets V1.75.2"><meta name="description" content="This document explains various interesting/complex/tricky aspects of JAXB, based on questions posted on the JAXB users forum and answers I provided. This is an ongoing work-in-progress. Any feedback appreciated."><link rel="home" href="index.html" title="JAXB Release Documentation"><link rel="up" href="index.html" title="JAXB Release Documentation"><link rel="prev" href="ch02.html" title="Release Notes"><link rel="next" href="ch04.html" title="Tools"><script xmlns:fo="http://www.w3.org/1999/XSL/Format" type="text/javascript">
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-2105126-1']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();
</script></head><body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"><div class="navheader"><table width="100%" summary="Navigation header"><tr><th colspan="3" align="center">JAXB Users Guide</th></tr><tr><td width="20%" align="left"><a accesskey="p" href="ch02.html">Prev</a>&nbsp;</td><th width="60%" align="center">&nbsp;</th><td width="20%" align="right">&nbsp;<a accesskey="n" href="ch04.html">Next</a></td></tr></table><hr></div><small xmlns:fo="http://www.w3.org/1999/XSL/Format" class="small">Links: <a href="index.html">Table of Contents</a> | <a href="release-documentation.html">Single HTML</a> | <a href="release-documentation.pdf">Single PDF</a></small><div lang="en" class="chapter" title="JAXB Users Guide" id="user-guide"><div class="titlepage"><div><div><h1 class="title">JAXB Users Guide</h1></div><div><div class="abstract" title="Abstract"><p class="title"><b>Abstract</b></p><p>This document explains various interesting/complex/tricky
            aspects of JAXB, based on questions posted on the <a class="link" href="http://forums.java.net/jive/forum.jspa?forumID=46" target="_top">JAXB
            users forum</a> and answers I provided. This is an ongoing
            work-in-progress. Any <a class="link" href="mailto:users@jaxb.java.net" target="_top">feedback</a>
            appreciated.</p></div></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl><dt><span class="section"><a href="ch03.html#compiling-xml-schema">1. Compiling XML Schema</a></span></dt><dd><dl><dt><span class="section"><a href="ch03.html#compiling-xml-schema-dealing-with-errors">1.1. Dealing with errors</a></span></dt><dt><span class="section"><a href="ch03.html#compiling-xml-schema-fixing-broken-references-in-schema">1.2. Fixing broken references in schema</a></span></dt><dt><span class="section"><a href="ch03.html#compiling-xml-schema-mapping-of-xs-any">1.3. Mapping of <code class="literal">&lt;xs:any /&gt;</code></a></span></dt><dt><span class="section"><a href="ch03.html#compiling-xml-schema-mapping-of-xs-element-to-jaxbelement">1.4. Mapping of <code class="literal">&lt;xs:element /&gt;</code> to JAXBElement</a></span></dt><dt><span class="section"><a href="ch03.html#compiling-xml-schema-how-modularization-of-schema-interacts-with-xjc">1.5. How modularization of schema interacts with XJC</a></span></dt><dt><span class="section"><a href="ch03.html#compiling-xml-schema-adding-behaviors">1.6. Adding behaviors</a></span></dt><dt><span class="section"><a href="ch03.html#compiling-xml-schema-avoid-strong-databinding">1.7. Avoid strong databinding</a></span></dt><dt><span class="section"><a href="ch03.html#compiling-xml-schema-working-with-generated-code-in-memory">1.8. Working with generated code in memory</a></span></dt></dl></dd><dt><span class="section"><a href="ch03.html#customization-of-schema-compilation">2. Customization of Schema Compilation</a></span></dt><dd><dl><dt><span class="section"><a href="ch03.html#customization-of-schema-compilation-customizing-java-packages">2.1. Customizing Java packages</a></span></dt><dt><span class="section"><a href="ch03.html#customization-of-schema-compilation-using-scd-for-customizations">2.2. Using SCD for customizations</a></span></dt><dt><span class="section"><a href="ch03.html#customization-of-schema-compilation-using-different-datatypes">2.3. Using different datatypes</a></span></dt></dl></dd><dt><span class="section"><a href="ch03.html#annotating-your-classes">3. Annotating Your Classes</a></span></dt><dd><dl><dt><span class="section"><a href="ch03.html#annotating-your-classes-mapping-your-favorite-class">3.1. Mapping your favorite class</a></span></dt><dt><span class="section"><a href="ch03.html#annotating-your-classes-mapping-interfaces">3.2. Mapping interfaces</a></span></dt><dt><span class="section"><a href="ch03.html#annotating-your-classes-evolving-annotated-classes">3.3. Evolving annotated classes</a></span></dt><dt><span class="section"><a href="ch03.html#annotating-your-classes-xml-layout-and-in-memory-data-layout">3.4. XML layout and in-memory data layout</a></span></dt><dt><span class="section"><a href="ch03.html#annotating-your-classes-mapping-cyclic-references-to-xml">3.5. Mapping cyclic references to XML</a></span></dt></dl></dd><dt><span class="section"><a href="ch03.html#unmarshalling">4. Unmarshalling</a></span></dt><dd><dl><dt><span class="section"><a href="ch03.html#unmarshalling-xmlrootelement-and-unmarshalling">4.1. <code class="literal">@XmlRootElement</code> and unmarshalling</a></span></dt><dt><span class="section"><a href="ch03.html#unmarshalling-unmarshalling-is-not-working-help">4.2. Unmarshalling is not working! Help!</a></span></dt><dt><span class="section"><a href="ch03.html#unmarshalling-element-default-values-and-unmarshalling">4.3. Element default values and unmarshalling</a></span></dt><dt><span class="section"><a href="ch03.html#unmarshalling-dealing-with-large-documents">4.4. Dealing with large documents</a></span></dt></dl></dd><dt><span class="section"><a href="ch03.html#marshalling">5. Marshalling</a></span></dt><dd><dl><dt><span class="section"><a href="ch03.html#marshalling-changing-prefixes">5.1. Changing prefixes</a></span></dt><dt><span class="section"><a href="ch03.html#marshalling-element-default-values-and-marshalling">5.2. Element default values and marshalling</a></span></dt><dt><span class="section"><a href="ch03.html#marshalling-different-ways-of-marshalling">5.3. Different ways of marshalling</a></span></dt><dt><span class="section"><a href="ch03.html#marshalling-interaction-between-marshalling-and-dom">5.4. Interaction between marshalling and DOM</a></span></dt></dl></dd><dt><span class="section"><a href="ch03.html#schema-generation">6. Schema Generation</a></span></dt><dd><dl><dt><span class="section"><a href="ch03.html#schema-generation-invoking-schemagen-programatically">6.1. Invoking schemagen programatically</a></span></dt><dt><span class="section"><a href="ch03.html#schema-generation-generating-schema-that-you-want">6.2. Generating Schema that you want</a></span></dt></dl></dd><dt><span class="section"><a href="ch03.html#deployment">7. Deployment</a></span></dt><dd><dl><dt><span class="section"><a href="ch03.html#deployment-migrating-jaxb-2-0-applications-to-javase-6">7.1. Migrating JAXB 2.0 applications to JavaSE 6</a></span></dt><dt><span class="section"><a href="ch03.html#deployment-which-jaxb-ri-is-included-in-which-jdk">7.2. Which JAXB RI is included in which JDK?</a></span></dt><dt><span class="section"><a href="ch03.html#deployment-running-jaxb-1-0-and-2-x-side-by-side">7.3. Running JAXB 1.0 and 2.x side by side</a></span></dt><dt><span class="section"><a href="ch03.html#deployment-migrating-jaxb-1-0-applications-to-jaxb-2-x">7.4. Migrating JAXB 1.0 applications to JAXB 2.x</a></span></dt><dt><span class="section"><a href="ch03.html#deployment-runtime-errors">7.5. Runtime Errors</a></span></dt></dl></dd><dt><span class="section"><a href="ch03.html#other-miscellaneous-topics">8. Other Miscellaneous Topics</a></span></dt><dd><dl><dt><span class="section"><a href="ch03.html#other-miscellaneous-topics-performance-and-thread-safety">8.1. Performance and thread-safety</a></span></dt><dt><span class="section"><a href="ch03.html#other-miscellaneous-topics-compiling-dtd">8.2. Compiling DTD</a></span></dt><dt><span class="section"><a href="ch03.html#other-miscellaneous-topics-using-jaxb-from-maven">8.3. Using JAXB from Maven</a></span></dt><dt><span class="section"><a href="ch03.html#other-miscellaneous-topics-designing-a-client-server-protocol-in-xml">8.4. Designing a client/server protocol in XML</a></span></dt><dt><span class="section"><a href="ch03.html#other-miscellaneous-topics-contributing-to-this-guide">8.5. Contributing to this Guide</a></span></dt></dl></dd></dl></div><div lang="en" class="section" title="1.&nbsp;Compiling XML Schema"><div class="titlepage"><div><div><h2 class="title" style="clear: both" id="compiling-xml-schema">1.&nbsp;Compiling XML Schema</h2></div></div></div><div lang="en" class="section" title="1.1.&nbsp;Dealing with errors"><div class="titlepage"><div><div><h3 class="title" id="compiling-xml-schema-dealing-with-errors">1.1.&nbsp;Dealing with errors</h3></div></div></div><div class="section" title="1.1.1.&nbsp;Schema errors"><div class="titlepage"><div><div><h4 class="title" id="Schema_errors">1.1.1.&nbsp;Schema errors</h4></div></div></div><p>Because XML Schema is so complicated, and because there are a
        lot of tools out there do not implement the spec correctly, it is
        often the case that a schema you are trying to compile has some real
        errors in it. When this is the case, you'll see XJC reporting somewhat
        cryptic errors such as <code class="literal">rcase-RecurseLax.2: There is not a
        complete functional mapping between the particles.</code></p><p>The JAXB RI uses the schema correctness checker from the
        underlying JAXP implementation, which is the JAXP RI in a typical
        setup. The JAXP RI is one of the most conformant schema validators,
        and therefore most likely correct. So the first course of action
        usually is to fix problems in the schema.</p><p>However, in some situations, you might not have an authority to
        make changes to the schema. If that is the case and you really need to
        compile the schema, you can bypass the correctness check by using the
        <code class="option">-nv</code> option in XJC. When you do this, keep in mind
        that you are possibly feeding "garbage" in, so you may see XJC choke
        with some random exception.</p></div><div class="section" title="1.1.2.&nbsp;Property 'fooBarZot' is already defined"><div class="titlepage"><div><div><h4 class="title" id="Property__fooBarZot__is_already_defined">1.1.2.&nbsp;Property 'fooBarZot' is already defined</h4></div></div></div><p>One of the typical errors you'll see when compiling a complex
        schema is:</p><div class="example"><a name="d0e1468"></a><p class="title"><b>Example&nbsp;1.&nbsp;Multiple property definitions error</b></p><div class="example-contents"><pre class="programlisting">parsing a schema...
[ERROR] Property "MiOrMoOrMn" is already defined.
  line 132 of
file:/C:/kohsuke/Sun/JAXB/jaxb-unit/schemas/individual/MathML2/presentation/scripts.xsd

[ERROR] The following location is relevant to the above error
  line 138 of
file:/C:/kohsuke/Sun/JAXB/jaxb-unit/schemas/individual/MathML2/presentation/scripts.xsd</pre></div></div><br class="example-break"><p>This is an actual example of the offending part of a schema,
        taken from MathML. If you go to line 132 of
        <code class="filename">scripts.xsd</code>, you'll see that it has a somewhat
        complicated content model definition:</p><div class="example"><a name="d0e1478"></a><p class="title"><b>Example&nbsp;2.&nbsp;Multiple property definitions in MathML</b></p><div class="example-contents"><pre class="programlisting"><span class="ReservedWord">&lt;xs:group</span> <span class="Identifier">name</span>=<span class="String">"mmultiscripts.content"</span><span class="ReservedWord">&gt;</span>
    <span class="ReservedWord">&lt;xs:sequence&gt;</span>
        <span class="ReservedWord">&lt;xs:group</span> <span class="Identifier">ref</span>=<span class="String">"Presentation-expr.class"</span><span class="ReservedWord">/&gt;</span>
        <span class="ReservedWord">&lt;xs:sequence</span> <span class="Identifier">minOccurs</span>=<span class="String">"0"</span> <span class="Identifier">maxOccurs</span>=<span class="String">"unbounded"</span><span class="ReservedWord">&gt;</span>      <span class="Comment">&lt;!-- line 132 --&gt;</span>
            <span class="ReservedWord">&lt;xs:group</span> <span class="Identifier">ref</span>=<span class="String">"Presentation-expr-or-none.class"</span><span class="ReservedWord">/&gt;</span>
            <span class="ReservedWord">&lt;xs:group</span> <span class="Identifier">ref</span>=<span class="String">"Presentation-expr-or-none.class"</span><span class="ReservedWord">/&gt;</span>
        <span class="ReservedWord">&lt;/xs:sequence&gt;</span>
        <span class="ReservedWord">&lt;xs:sequence</span> <span class="Identifier">minOccurs</span>=<span class="String">"0"</span><span class="ReservedWord">&gt;</span>
            <span class="ReservedWord">&lt;xs:element</span> <span class="Identifier">ref</span>=<span class="String">"mprescripts"</span><span class="ReservedWord">/&gt;</span>
            <span class="ReservedWord">&lt;xs:sequence</span> <span class="Identifier">maxOccurs</span>=<span class="String">"unbounded"</span><span class="ReservedWord">&gt;</span>                 <span class="Comment">&lt;!-- line 138 --&gt;</span>
                <span class="ReservedWord">&lt;xs:group</span> <span class="Identifier">ref</span>=<span class="String">"Presentation-expr-or-none.class"</span><span class="ReservedWord">/&gt;</span>
                <span class="ReservedWord">&lt;xs:group</span> <span class="Identifier">ref</span>=<span class="String">"Presentation-expr-or-none.class"</span><span class="ReservedWord">/&gt;</span>
            <span class="ReservedWord">&lt;/xs:sequence&gt;</span>
        <span class="ReservedWord">&lt;/xs:sequence&gt;</span>
    <span class="ReservedWord">&lt;/xs:sequence&gt;</span>
<span class="ReservedWord">&lt;/xs:group&gt;</span></pre></div></div><br class="example-break"><p>This is a standard technique in designing a schema. When you
        want to say "in this element, <code class="literal">B</code> can occur arbitrary
        times, but <code class="literal">C</code> can occur only up to once", you write
        this as <code class="literal">B*,(C,B*)?</code>. This, however, confuses JAXB,
        because it tries to bind the first <code class="literal">B</code> to its own
        property, then <code class="literal">C</code> to its own property, then the
        second <code class="literal">B</code> to its own property, and so we end up
        having a collision again.</p><p>In this particular case, <code class="literal">B</code> isn't a single
        element but it's a choice of large number of elements abstracted away
        in <code class="literal">&lt;xs:group&gt;</code>s, so they are hard to see. But
        if you see the same content model referring to the same element/group
        twice in a different place, you can suspect this.</p><p>In this case, you'd probably want the whole thing to map to a
        single list so that you can retain the order those elements show up in
        the document. You can do this by putting the same
        <code class="literal">&lt;jaxb:property&gt;</code> customization on the whole
        "<code class="literal">mmultiscripts.content</code>" model group, like this (or
        you can do it externally with XPath):</p><div class="example"><a name="d0e1519"></a><p class="title"><b>Example&nbsp;3.&nbsp;How to fix the problem?</b></p><div class="example-contents"><pre class="programlisting"><span class="ReservedWord">&lt;xs:groupname="mmultiscripts.content"&gt;</span>
<span class="ReservedWord">&lt;xs:annotation&gt;</span>
    <span class="ReservedWord">&lt;xs:appinfo&gt;</span>
        <span class="ReservedWord">&lt;jaxb:propertyname="content"/&gt;</span>
    <span class="ReservedWord">&lt;/xs:appinfo&gt;</span>
<span class="ReservedWord">&lt;/xs:annotation&gt;</span>
<span class="ReservedWord">&lt;xs:sequence&gt;</span>
<span class="ReservedWord">&lt;xs:groupref="Presentation-expr.class"/&gt;</span></pre></div></div><br class="example-break"><p>Another way to fix this problem is to use <a class="link" href="http://weblogs.java.net/blog/kohsuke/archive/2006/03/simple_and_bett.html" target="_top">the
        simpler and better binding mode</a> in XJC, which is a JAXB RI
        vendor extension.</p></div><div class="section" title="1.1.3.&nbsp;Two declarations cause a collision in the ObjectFactory class"><div class="titlepage"><div><div><h4 class="title" id="Two_declarations_cause_a_collision_in_the_ObjectFactory_class">1.1.3.&nbsp;Two declarations cause a collision in the ObjectFactory
        class</h4></div></div></div><p>When schemas contain similar looking element/type names, they
        can result in "Two declarations cause a collision in the ObjectFactory
        class" errors. To be more precise, for each of all types and many
        elements (exactly what elements get a factory and what doesn't is bit
        tricky to explain), XJC produces one method on the
        <code class="literal">ObjectFactory</code> class in the same package. The
        <code class="literal">ObjectFactory</code> class is created for each package that XJC
        generates some files into. The name of the method is derived from XML
        element/type names, and the error is reported if two elements/types
        try to generate the same method name.</p><p>There are two approaches to fix this problem. If the collision
        is coming from two different schemas with different target namespaces,
        then you can easily avoid the collision by compiling them into
        different Java packages. To do this, use <a class="link" href="http://jaxb.java.net/nonav/2.0/binding-customization/http.java.sun.com.xml.n/element/schemabindings.html" target="_top"><code class="literal">&lt;schemabindings&gt;</code></a>
        customization on two schemas and specify the package name.</p><p>Another way to fix this problem is to use <a class="link" href="http://jaxb.java.net/nonav/2.0/binding-customization/http.java.sun.com.xml.n/element/factorymethod.html" target="_top"><code class="literal">&lt;factoryMethod&gt;</code></a>
        customization on two conflicting elements/types to specify different
        factory method names. This can be used in all cases, but if you have a
        large number of conflicts, you'll have to specify this customization
        one by one.</p><p>Notice that <a class="link" href="http://jaxb.java.net/nonav/2.0/binding-customization/http.java.sun.com.xml.n/element/class.html" target="_top"><code class="literal">&lt;class&gt;</code></a>
        customization doesn't affect the <code class="literal">ObjectFactory</code> method
        name by itself.</p></div><div class="section" title="1.1.4.&nbsp;Customization errors"><div class="titlepage"><div><div><h4 class="title" id="Customization_errors">1.1.4.&nbsp;Customization errors</h4></div></div></div><div class="section" title="1.1.4.1.&nbsp;XPath evaluation of ... results in empty target node"><div class="titlepage"><div><div><h5 class="title" id="XPath_evaluation_of_____results_in_empty_target_node">1.1.4.1.&nbsp;XPath evaluation of ... results in empty target
            node</h5></div></div></div><p>External JAXB customizations are specified by using XPath
            (or using <a class="link" href="http://jaxb.java.net/guide/customization-of-schema-compilation-using-scd-for-customizations" target="_top">SCD</a>.)
            This works by writing an XPath expression that matches a
            particular element in the schema document. For example, given the
            following schema and binding file:</p><div class="example"><a name="d0e1572"></a><p class="title"><b>Example&nbsp;4.&nbsp;Schema and external binding file</b></p><div class="example-contents"><p title="test.xsd"><b><code class="filename">test.xsd</code>.&nbsp;</b></p><pre class="programlisting"><span class="ReservedWord">&lt;xs:schema</span> <span class="Identifier">xmlns:xs</span>=<span class="String">"http://www.w3.org/2001/XMLSchema"</span><span class="ReservedWord">&gt;</span>
    <span class="ReservedWord">&lt;xs:complexTypename="foo"/&gt;</span>
<span class="ReservedWord">&lt;/xs:schema&gt;</span></pre><p title="test.xjb"><b><code class="filename">test.xjb</code>.&nbsp;</b></p><pre class="programlisting"><span class="ReservedWord">&lt;bindings</span> <span class="Identifier">version</span>=<span class="String">"2.0"</span> <span class="Identifier">xmlns</span>=<span class="String">"http://java.sun.com/xml/ns/jaxb"</span> <span class="Identifier">xmlns:xs</span>=<span class="String">"http://www.w3.org/2001/XMLSchema"</span><span class="ReservedWord">&gt;</span>
    <span class="ReservedWord">&lt;bindings</span> <span class="Identifier">schemaLocation</span>=<span class="String">"test.xsd"</span><span class="ReservedWord">&gt;</span>
        <span class="ReservedWord">&lt;bindings</span> <span class="Identifier">node</span>=<span class="String">"//xs:complexType[@name='foo']"</span><span class="ReservedWord">&gt;</span>
            <span class="ReservedWord">&lt;classname="Bar"/&gt;</span>
        <span class="ReservedWord">&lt;/bindings&gt;</span>
    <span class="ReservedWord">&lt;/bindings&gt;</span>
<span class="ReservedWord">&lt;/bindings&gt;</span></pre></div></div><br class="example-break"><p>will be interpreted as if the class customization is
            attached to the complex type '<code class="literal">foo</code>'.</p><p>For this to work, the XPath expression needs to match one
            and only one element in the schema document. When the XPath
            expression is incorrect and it didn't match anything, you get this
            "XPath evaluation of ... results in empty target node"
            problem.</p><p>Common causes of this problem include typos, incorrect
            namespace URI declarations, and misunderstanding of XPath.</p></div></div></div><div lang="en" class="section" title="1.2.&nbsp;Fixing broken references in schema"><div class="titlepage"><div><div><h3 class="title" id="compiling-xml-schema-fixing-broken-references-in-schema">1.2.&nbsp;Fixing broken references in schema</h3></div></div></div><p>Sometimes a schema may refer to another schema document without
    indicating where the schema file can be found, like this:</p><div class="example"><a name="d0e1604"></a><p class="title"><b>Example&nbsp;5.&nbsp;Schema reference without location</b></p><div class="example-contents"><pre class="programlisting"><span class="ReservedWord">&lt;xs:import</span> <span class="Identifier">namespace</span>=<span class="String">"http://www.w3.org/1999/xlink"</span><span class="ReservedWord"> /&gt;</span></pre></div></div><br class="example-break"><p>In other cases, a schema may refer to another schema on the network,
    which often slows down your compilation process and makes it unreliable.
    Yet in some other cases, a schema may reference another schema in relative
    path, and that may not match your directory structure.</p><p>XJC bundles a <a class="link" href="http://xml.apache.org/commons/components/resolver/resolver-article.html" target="_top">catalog
    resolver</a> so that you can work around these situations without
    changing the schema documents. The main idea behind the catalog is
    "redirection" --- when XJC is about to fetch resources, it will consult
    the catalog resolver to see if it can find the resource elsewhere (which
    is usually your local resources.)</p><div class="section" title="1.2.1.&nbsp;Catalog format"><div class="titlepage"><div><div><h4 class="title" id="Catalog_format">1.2.1.&nbsp;Catalog format</h4></div></div></div><p>The catalog resolver supports many different formats, but the
        easiest one is a line based <code class="filename">*.cat</code> format. Other than
        comments and empty lines, the file mainly consists of two kinds of
        declarations, <code class="literal">SYSTEM</code>, and
        <code class="literal">PUBLIC</code>.</p><div class="example"><a name="d0e1630"></a><p class="title"><b>Example&nbsp;6.&nbsp;<code class="filename">sample-catalog.cat</code></b></p><div class="example-contents"><pre class="programlisting">--
  sample catalog file.

  double hyphens are used to begin and end a comment section.
--

SYSTEM "http://www.w3.org/2001/xml.xsd" "xml.xsd"

PUBLIC "-//W3C//DTD XMLSCHEMA 200102//EN" "s4s/XMLSchema.dtd"</pre></div></div><br class="example-break"></div><div class="section" title="1.2.2.&nbsp;Resolve by system ID"><div class="titlepage"><div><div><h4 class="title" id="Resolve_by_system_ID">1.2.2.&nbsp;Resolve by system ID</h4></div></div></div><p>The SYSTEM entry has the format of "SYSTEM
        <span class="emphasis"><em>REFERENCE</em></span> <span class="emphasis"><em>ACTUAL-LOCATION</em></span>",
        which defines a simple redirection. Every time XJC loads any resource
        (be it schemas, DTDs, any entities referenced within), it will first
        resolve relative paths to absolute paths, then looks for a matching
        <span class="emphasis"><em>REFERENCE</em></span> line. If it is found, the specified
        actual location is read instead. Otherwise XJC will attempt to resolve
        the absolutepath.</p><p><span class="emphasis"><em>ACTUAL-LOCATION</em></span> above accepts relative
        paths, and those are resolved against the catalog file itself (so in
        the above example, <code class="literal">xml.xsd</code> is assumed to be in the same
        directory with <code class="filename">sample-catalog.cat</code>.</p><p>What you need to be careful is the fact that the
        <span class="emphasis"><em>REFERENCE</em></span> portion must be absolute, and when XJC
        finds a reference in schema, it will first convert that to the
        absolute path before checking the catalog. So what this means is that
        if your schema is written like this:</p><div class="example"><a name="d0e1665"></a><p class="title"><b>Example&nbsp;7.&nbsp;Schema reference by relative path</b></p><div class="example-contents"><pre class="programlisting"><span class="ReservedWord">&lt;xs:import</span> <span class="Identifier">namespace</span>=<span class="String">"http://www.w3.org/1999/xlink"</span> <span class="Identifier">schemaLocation</span>=<span class="String">"xlink.xsd"</span><span class="ReservedWord"> /&gt;</span></pre></div></div><br class="example-break"><p>Then your catalog entry would have to look like this:</p><div class="example"><a name="d0e1672"></a><p class="title"><b>Example&nbsp;8.&nbsp;xlink.cat</b></p><div class="example-contents"><pre class="programlisting">-- this doesn't work because xlink.xsd will be turned into absolute path --
SYSTEM "xlink.xsd" "http://www.w3.org/2001/xlink.xsd"

-- this will work, assuming that the above schema is in /path/to/my/test.xsd --
SYSTEM "/path/to/my/xlink.xsd" "http://www.w3.org/2001/xlink.xsd"</pre></div></div><br class="example-break"></div><div class="section" title="1.2.3.&nbsp;Resolve by public ID / namespace URI"><div class="titlepage"><div><div><h4 class="title" id="Resolve_by_public_ID___namespace_URI">1.2.3.&nbsp;Resolve by public ID / namespace URI</h4></div></div></div><p>Another kind of entry has the format of "PUBLIC
        <span class="emphasis"><em>PUBLICID</em></span> <span class="emphasis"><em>ACTUAL-LOCATION</em></span>" or
        "PUBLIC <span class="emphasis"><em>NAMESPACEURI</em></span>
        <span class="emphasis"><em>ACTUAL-LOCATION</em></span>".</p><p>The "<code class="literal">PUBLICID</code>" version is used to resolve DTDs and entities in
        DTDs. But this type of entry is also used to resolve <code class="literal">&lt;xs:import&gt;</code>
        statements. XJC will match the value of the namespace attribute and
        see if there's any matching entry. So given a schema like this:</p><div class="example"><a name="d0e1702"></a><p class="title"><b>Example&nbsp;9.&nbsp;Schema import</b></p><div class="example-contents"><pre class="programlisting"><span class="ReservedWord">&lt;xs:import</span> <span class="Identifier">namespace</span>=<span class="String">"http://www.w3.org/1999/xlink"</span> <span class="Identifier">schemaLocation</span>=<span class="String">"xlink.xsd"</span><span class="ReservedWord"> /&gt;</span>
<span class="ReservedWord">&lt;xs:import</span> <span class="Identifier">namespace</span>=<span class="String">"http://www.w3.org/1998/Math/MathML"</span><span class="ReservedWord"> /&gt;</span></pre></div></div><br class="example-break"><p>The following catalog entries will match them.</p><div class="example"><a name="d0e1709"></a><p class="title"><b>Example&nbsp;10.&nbsp;by-publicid.cat</b></p><div class="example-contents"><pre class="programlisting">PUBLIC "http://www.w3.org/1999/xlink" "http://www.w3.org/2001/xlink.xsd"
PUBLIC "http://www.w3.org/1998/Math/MathML" "/path/to/my/mathml.xsd"</pre></div></div><br class="example-break"><p>As you can see, XJC will check the PUBLIC entries regardless of
        whether <code class="literal">&lt;xs:import&gt;</code> has the schemaLocation attribute or not. As
        with the case with the SYSTEM entry, the ACTUAL-LOCATION part can be
        relative to the location of the catalog file.</p></div><div class="section" title="1.2.4.&nbsp;Specifying the catalog file"><div class="titlepage"><div><div><h4 class="title" id="Specifying_the_catalog_file">1.2.4.&nbsp;Specifying the catalog file</h4></div></div></div><p>Once you write a catalog file, you'd need to specify that when
        you invoke XJC.</p><div class="variablelist"><dl><dt><span class="term">CLI</span></dt><dd><p>To do this from the CLI, use the <code class="option">-catalog</code> option. See <a class="link" href="/nonav/2.1.4/docs/xjc.html" target="_top"><span class="command"><strong>xjc
                    -help</strong></span> for more details</a>.</p></dd><dt><span class="term">Ant</span></dt><dd><p>Use the catalog attribute on the <code class="literal">&lt;xjc&gt;</code> task.
                    See <a class="link" href="/nonav/2.1.4/docs/xjcTask.html" target="_top">XJC
                    ant task documentation</a> for more details.</p></dd><dt><span class="term">Maven</span></dt><dd><p>For the <a class="link" href="https://maven-jaxb2-plugin.java.net/" target="_top">Maven
                    plugin</a>, use the <code class="literal">&lt;catalog&gt;</code> element in the
                    configuration: </p><div class="informalexample"><pre class="programlisting">&lt;plugin&gt;
    &lt;groupId&gt;org.jvnet.jaxb2.maven2&lt;/groupId&gt;
    &lt;artifactId&gt;maven-jaxb2-plugin&lt;/artifactId&gt;
    &lt;configuration&gt;
        &lt;!-- relative to the POM file --&gt;
        &lt;catalog&gt;mycatalog.cat&lt;/catalog&gt;
    &lt;/copnfiguration&gt;
&lt;/plugin&gt;</pre></div></dd></dl></div></div><div class="section" title="1.2.5.&nbsp;Debugging catalog file"><div class="titlepage"><div><div><h4 class="title" id="Debugging_catalog_file">1.2.5.&nbsp;Debugging catalog file</h4></div></div></div><p>If you are trying to write a catalog file and banging your head
        against a wall because it's not working, you should enable the verbose
        option of the catalog resolver. How you do this depends on what
        interface you use:</p><div class="variablelist"><dl><dt><span class="term">CLI</span></dt><dd><p>Specify <span class="command"><strong>export
                    XJC_OPTS="-Dxml.catalog.verbosity=999"</strong></span> then run
                    XJC.</p></dd><dt><span class="term">Ant/Maven</span></dt><dd><p>Add <code class="literal">-Dxml.catalog.verbosity=999</code> as a
                    command line option to Ant/Maven.</p></dd></dl></div><p>If you are otherwise invoking XJC programmatically, you can set
        the above system property before invoking XJC.</p></div></div><div lang="en" class="section" title="1.3.&nbsp;Mapping of <xs:any /&gt;"><div class="titlepage"><div><div><h3 class="title" id="compiling-xml-schema-mapping-of-xs-any">1.3.&nbsp;Mapping of <code class="literal">&lt;xs:any /&gt;</code></h3></div></div></div><p>XJC binds <code class="literal">&lt;xs:any /&gt;</code> in the following ways:</p><div class="section" title="1.3.1.&nbsp;processContents=&#34;skip&#34;"><div class="titlepage"><div><div><h4 class="title" id="processContents__skip_">1.3.1.&nbsp;<code class="literal">processContents="skip"</code></h4></div></div></div><p><code class="literal">&lt;xs:any /&gt;</code> with <code class="code">processContents=skip</code> means
        any well-formed XML elements can be placed. Therefore, XJC binds this
        to DOM <code class="literal">Element</code> interface.</p><div class="example"><a name="d0e1817"></a><p class="title"><b>Example&nbsp;11.&nbsp;Any/Skip schema</b></p><div class="example-contents"><pre class="programlisting"><span class="ReservedWord">&lt;xs:element</span> <span class="Identifier">name</span>=<span class="String">"person"</span><span class="ReservedWord">&gt;</span>
  <span class="ReservedWord">&lt;xs:complexType&gt;</span>
    <span class="ReservedWord">&lt;xs:sequence&gt;</span>
      <span class="ReservedWord">&lt;xs:element</span> <span class="Identifier">name</span>=<span class="String">"name"</span> <span class="Identifier">type</span>=<span class="String">"xs:string"</span><span class="ReservedWord"> /&gt;</span>
      <span class="ReservedWord">&lt;xs:any</span> <span class="Identifier">processContents</span>=<span class="String">"skip"</span> <span class="Identifier">maxOccurs</span>=<span class="String">"unbounded"</span> <span class="Identifier">minOccurs</span>=<span class="String">"0"</span><span class="ReservedWord"> /&gt;</span>
    <span class="ReservedWord">&lt;/xs:sequence&gt;</span>
  <span class="ReservedWord">&lt;/xs:complexType&gt;</span>
<span class="ReservedWord">&lt;/xs:element&gt;</span></pre></div></div><br class="example-break"><div class="example"><a name="d0e1822"></a><p class="title"><b>Example&nbsp;12.&nbsp;Any/Skip binding</b></p><div class="example-contents"><pre class="programlisting"><span class="ReservedWord">import</span> org.w3c.dom.Element;

<span class="Annotation">@XmlRootElement</span>
<span class="ReservedWord">class</span> Person {
  <span class="ReservedWord">public</span> String getName();
  <span class="ReservedWord">public</span> <span class="ReservedWord">void</span> setName(String);

  <span class="Annotation">@XmlAnyElement</span>
  <span class="ReservedWord">public</span> List&lt;Element&gt; getAny();
}</pre></div></div><br class="example-break"></div><div class="section" title="1.3.2.&nbsp;processContents=&#34;strict&#34;"><div class="titlepage"><div><div><h4 class="title" id="processContents__strict_">1.3.2.&nbsp;<code class="literal">processContents="strict"</code></h4></div></div></div><p><code class="literal">&lt;xs:any /&gt;</code> with <code class="code">processContents=strict</code> (or
        <code class="literal">&lt;xs:any /&gt;</code> without any processContents attribute, since it
        defaults to "strict") means any XML elements placed here must have
        corresponding schema definitions. This mode is not what people
        typically expect as "<code class="literal">wildcard</code>", but this is the default. The following
        shows this binding. (<code class="code">lax=true</code> is unintuitive, but it's
        not an error in this document):</p><div class="example"><a name="d0e1847"></a><p class="title"><b>Example&nbsp;13.&nbsp;Any/Strict schema</b></p><div class="example-contents"><pre class="programlisting"><span class="ReservedWord">&lt;xs:element</span> <span class="Identifier">name</span>=<span class="String">"person"</span><span class="ReservedWord">&gt;</span>
  <span class="ReservedWord">&lt;xs:complexType&gt;</span>
    <span class="ReservedWord">&lt;xs:sequence&gt;</span>
      <span class="ReservedWord">&lt;xs:element</span> <span class="Identifier">name</span>=<span class="String">"name"</span> <span class="Identifier">type</span>=<span class="String">"xs:string"</span><span class="ReservedWord"> /&gt;</span>
      <span class="ReservedWord">&lt;xs:any</span> <span class="Identifier">maxOccurs</span>=<span class="String">"unbounded"</span> <span class="Identifier">minOccurs</span>=<span class="String">"0"</span><span class="ReservedWord"> /&gt;</span>
    <span class="ReservedWord">&lt;/xs:sequence&gt;</span>
  <span class="ReservedWord">&lt;/xs:complexType&gt;</span>
<span class="ReservedWord">&lt;/xs:element&gt;</span></pre></div></div><br class="example-break"><div class="example"><a name="d0e1852"></a><p class="title"><b>Example&nbsp;14.&nbsp;Any/Strict binding</b></p><div class="example-contents"><pre class="programlisting"><span class="Annotation">@XmlRootElement</span>
<span class="ReservedWord">class</span> Person {
  <span class="ReservedWord">public</span> String getName();
  <span class="ReservedWord">public</span> <span class="ReservedWord">void</span> setName(String);

  <span class="Annotation">@XmlAnyElement(lax=true)</span>
  <span class="ReservedWord">public</span> List&lt;Object&gt; getAny();
}</pre></div></div><br class="example-break"><p>JAXB binds any such element to an <code class="literal">Object</code>, and
        during unmarshalling, all elements encountered are unmarshalled into
        corresponding JAXB objects (including <code class="literal">JAXBElement</code>s if
        necessary) and placed in this field. If it encounters elements that
        cannot be unmarshalled, DOM elements are produced instead.</p><p>At runtime, you can place either DOM elements or some JAXB
        objects that map to elements. A typical mistake is to put a
        <code class="literal">String</code> that contains XML fragment, but this won't work;
        you'd have to first read that into a DOM.</p></div><div class="section" title="1.3.3.&nbsp;processContents=&#34;lax&#34;"><div class="titlepage"><div><div><h4 class="title" id="processContents__lax_">1.3.3.&nbsp;<code class="literal">processContents="lax"</code></h4></div></div></div><p><code class="literal">&lt;xs:any /&gt;</code> with <code class="code">processContents=lax</code> means any
        XML elements can be placed here, but if their element names match
        those defined in the schema, they have to be valid. XJC actually
        handles this exactly like processContents='strict', since the strict
        binding allows unknown elements anyway.</p></div></div><div lang="en" class="section" title="1.4.&nbsp;Mapping of <xs:element /&gt; to JAXBElement"><div class="titlepage"><div><div><h3 class="title" id="compiling-xml-schema-mapping-of-xs-element-to-jaxbelement">1.4.&nbsp;Mapping of <code class="literal">&lt;xs:element /&gt;</code> to JAXBElement</h3></div></div></div><p>Sometimes XJC binds an element declaration to
    <code class="literal">JAXBElement</code>. Sometimes XJC binds an element declaration to a
    Java class. What makes this difference?</p><p>TODO: Copy from <a class="link" href="http://weblogs.java.net/blog/kohsuke/archive/2006/03/why_does_jaxb_p.html" target="_top">http://weblogs.java.net/blog/kohsuke/archive/2006/03/why_does_jaxb_p.html</a></p></div><div lang="en" class="section" title="1.5.&nbsp;How modularization of schema interacts with XJC"><div class="titlepage"><div><div><h3 class="title" id="compiling-xml-schema-how-modularization-of-schema-interacts-with-xjc">1.5.&nbsp;How modularization of schema interacts with XJC</h3></div></div></div><p>Over time schema authors have developed several techniques to
    modularize large schemas. Some of those techniques have some noteworthy
    interactions with XJC.</p><div class="section" title="1.5.1.&nbsp;Chameleon schema"><div class="titlepage"><div><div><h4 class="title" id="Chameleon_schema">1.5.1.&nbsp;Chameleon schema</h4></div></div></div><p><a class="link" href="http://www.xfront.com/ZeroOneOrManyNamespaces.html#mixed" target="_top">Chameleon
        schema"</a> (<a class="link" href="http://www.google.com/search?q=chameleon+schema" target="_top">read
        more</a>, in particular <a class="link" href="http://www.kohsuke.org/xmlschema/XMLSchemaDOsAndDONTs.html#avoid_chameleon" target="_top">this</a>)
        is a technique used to define multiple almost-identical sets of
        definitions into multiple namespaces from a single schema
        document.</p><p>For example, with this technique, you can write just one "foo"
        complex type and define it into namespace X and Y. In this case, one
        tends to hope that XJC will only give you one <code class="literal">Foo</code> class
        for this, but unfortunately because it's actually defined in two
        namespaces, JAXB needs two Java classes to distinguish <code class="literal">X:foo</code> and
        <code class="literal">Y:foo</code>, so you'll get multiple copies.</p><p>If you find this to be problematic, there are a few ways to work
        around the problem.</p><div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem"><p>If you are in control of the schema, see if you can
                rewrite the schema to avoid using this technique. In some
                cases, the schema doesn't actually exploit the additional
                power of this technique, so this translation can be done
                without affecting XML instance documents. In some other cases,
                the chameleon schema can be argued as a bad schema design, as
                it duplicates definitions in many places.</p></li><li class="listitem"><p>If you are not in control of the schema, see if you can
                rewrite the schema nevertheless. This will only work if your
                transformation doesn't affect XML instance documents.</p></li><li class="listitem"><p>Perhaps there can be a plugin that eases the pain of
                this, such as by defining common interfaces among
                copies.</p></li></ol></div></div></div><div lang="en" class="section" title="1.6.&nbsp;Adding behaviors"><div class="titlepage"><div><div><h3 class="title" id="compiling-xml-schema-adding-behaviors">1.6.&nbsp;Adding behaviors</h3></div></div></div><p><span class="emphasis"><em>Adding behaviors to the generated code is one area that
    still needs improvement. Your feedback is appreciated.</em></span></p><p>Suppose if JAXB generated the following classes.</p><div class="example"><a name="d0e1948"></a><p class="title"><b>Example&nbsp;15.&nbsp;Simple JAXB Generated Code</b></p><div class="example-contents"><pre class="programlisting"><span class="ReservedWord">package</span> org.acme.foo;

<span class="Annotation">@XmlRootElement</span>
<span class="ReservedWord">class</span> Person {
  <span class="ReservedWord">private</span> String name;

  <span class="ReservedWord">public</span> String getName() { <span class="ReservedWord">return</span> name; }
  <span class="ReservedWord">public</span> <span class="ReservedWord">void</span> setName(String) { <span class="ReservedWord">this</span>.name=name; }
}

<span class="Annotation">@XmlRegistry</span>
<span class="ReservedWord">class</span> ObjectFactory {
  Person createPerson() { ... }
}</pre></div></div><br class="example-break"><p>To add a behavior, first write a class that extends from
    <code class="literal">Person</code>. You also need to extend ObjectFactory to return this
    new class. Notice that neither classes have any JAXB annotation, and I put
    them in a separate package. This is because we'd like
    <code class="literal">PersonEx</code> class to be used in place of <code class="literal">Person</code>,
    and we don't want <code class="literal">PersonEx</code> to be bound to its own XML
    type.</p><div class="example"><a name="d0e1967"></a><p class="title"><b>Example&nbsp;16.&nbsp;Extended Person class</b></p><div class="example-contents"><pre class="programlisting"><span class="ReservedWord">package</span> org.acme.foo.impl;

<span class="ReservedWord">class</span> PersonEx <span class="ReservedWord">extends</span> Person {
  <span class="Annotation">@Override</span>
  <span class="ReservedWord">public</span> <span class="ReservedWord">void</span> setName(String name) {
    <span class="ReservedWord">if</span>(name.length()&lt;<span class="Numeric">3</span>) <span class="ReservedWord">throw</span> <span class="ReservedWord">new</span> IllegalArgumentException();
    <span class="ReservedWord">super</span>.setName(name);
  }
}

<span class="Annotation">@XmlRegistry</span>
<span class="ReservedWord">class</span> ObjectFactoryEx <span class="ReservedWord">extends</span> ObjectFactory {
  <span class="Annotation">@Override</span>
  Person createPerson() {
    <span class="ReservedWord">return</span> <span class="ReservedWord">new</span> PersonEx();
  }
}</pre></div></div><br class="example-break"><p>At runtime, you can create <code class="literal">JAXBContext</code> normally, like
    this.</p><div class="example"><a name="d0e1977"></a><p class="title"><b>Example&nbsp;17.&nbsp;Creating JAXBContext</b></p><div class="example-contents"><pre class="programlisting">JAXBContext context = JAXBContext.newInstance(ObjectFactory.<span class="ReservedWord">class</span>);
<span class="Comment">// or JAXBContext.newInstance("org.acme.foo");</span></pre></div></div><br class="example-break"><p><code class="literal">PersonEx</code> can be marshalled out just like
    <code class="literal">Person</code>:</p><div class="example"><a name="d0e1989"></a><p class="title"><b>Example&nbsp;18.&nbsp;Marshalling</b></p><div class="example-contents"><pre class="programlisting">Person p = <span class="ReservedWord">new</span> PersonEx();
context.createMarshaller().marshal(p,System.out);
<span class="Comment">// this will produce &lt;person /&gt;</span></pre></div></div><br class="example-break"><p>To unmarshal XML documents into <code class="literal">PersonEx</code>, you'll need
    to configure the unmarshaller to use your <code class="literal">ObjectFactoryEx</code> as
    the factory, like this:</p><div class="example"><a name="d0e2002"></a><p class="title"><b>Example&nbsp;19.&nbsp;Unmarshalling</b></p><div class="example-contents"><pre class="programlisting">Unmarshaller u = context.createUnmarshaller();
u.setProperty(<span class="String">"com.sun.xml.bind.ObjectFactory"</span>,<span class="ReservedWord">new</span> ObjectFactoryEx());
PersonEx p = (PersonEx)u.unmarshal(<span class="ReservedWord">new</span> StringReader(<span class="String">"&lt;person /&gt;"</span>));</pre></div></div><br class="example-break"><p>If you have multiple packages and thus multiple
    <code class="literal">ObjectFactory</code>s, you can pass in an array of them (<code class="code">new
    Object[]{new OFEx1(),new OFEx2(),...}</code>.)</p><div class="section" title="1.6.1.&nbsp;Inserting your class in the middle"><div class="titlepage"><div><div><h4 class="title" id="Inserting_your_class_in_the_middle">1.6.1.&nbsp;Inserting your class in the middle</h4></div></div></div><p>If you have a type hierarchy and would like to insert your class
        in the middle, you can use the combination of <a class="link" href="http://jaxb.java.net/nonav/jaxb20-fcs/docs/api/index.html?javax/xml/bind/annotation//1.6.1XmlTransient.html" target="_top"><code class="literal">XmlTransient</code></a>
        and <code class="literal">@implClass</code> of <a class="link" href="http://jaxb.java.net/nonav/2.0/binding-customization/http.java.sun.com.xml.n/element/class.html" target="_top"><code class="literal">&lt;class&gt;</code></a>
        customization. See the following example:</p><div class="example"><a name="d0e2031"></a><p class="title"><b>Example&nbsp;20.&nbsp;Hierarchy of types and <code class="literal">&lt;jaxb:class implClass&gt;</code></b></p><div class="example-contents"><pre class="programlisting"><span class="ReservedWord">&lt;xs:schema</span> <span class="Identifier">...&gt;</span>
  <span class="Identifier">&lt;xs:complexType</span> <span class="Identifier">name</span>=<span class="String">"vehicle"</span><span class="ReservedWord">&gt;</span>
    <span class="ReservedWord">&lt;xs:annotation&gt;</span><span class="ReservedWord">&lt;xs:appinfo&gt;</span>
      <span class="ReservedWord">&lt;jaxb:class</span> <span class="Identifier">implClass</span>=<span class="String">"MyVehicle"</span><span class="ReservedWord"> /&gt;</span>
    <span class="ReservedWord">&lt;/xs:appinfo&gt;</span><span class="ReservedWord">&lt;/xs:annotation&gt;</span>
  <span class="ReservedWord">&lt;/xs:complexType&gt;</span>

  <span class="ReservedWord">&lt;xs:complexType</span> <span class="Identifier">name</span>=<span class="String">"car"</span><span class="ReservedWord">&gt;</span>
    <span class="ReservedWord">&lt;xs:complexContent&gt;</span>
      <span class="ReservedWord">&lt;xs:extension</span> <span class="Identifier">base</span>=<span class="String">"vehicle"</span><span class="ReservedWord"> /&gt;</span>
    <span class="ReservedWord">&lt;/xs:complexContent&gt;</span>
  <span class="ReservedWord">&lt;/xs:complexType&gt;</span>

  <span class="ReservedWord">&lt;xs:complexType</span> <span class="Identifier">name</span>=<span class="String">"bicycle"</span><span class="ReservedWord">&gt;</span>
    <span class="ReservedWord">&lt;xs:complexContent&gt;</span>
      <span class="ReservedWord">&lt;xs:extension</span> <span class="Identifier">base</span>=<span class="String">"vehicle"</span><span class="ReservedWord"> /&gt;</span>
    <span class="ReservedWord">&lt;/xs:complexContent&gt;</span>
  <span class="ReservedWord">&lt;/xs:complexType&gt;</span>
<span class="ReservedWord">&lt;/xs:schema&gt;</span></pre></div></div><br class="example-break"><div class="example"><a name="d0e2038"></a><p class="title"><b>Example&nbsp;21.&nbsp;This creates a class hierarchy like the following (among
            the generated Java code):</b></p><div class="example-contents"><pre class="programlisting">            Vehicle
               ^
               |
            MyVehicle
               ^
          _____|______
         |            |
        Car          Bicycle</pre></div></div><br class="example-break"><p>You'll then manually write <code class="literal">MyVehicle</code> class that
        extends from <code class="literal">Vehicle</code>. Annotate this class with <a class="link" href="http://jaxb.java.net/nonav/jaxb20-fcs/docs/api/index.html?javax/xml/bind/annotation//1.6.1XmlTransient.html" target="_top"><code class="literal">XmlTransient</code></a>
        to achieve the desired effect.</p></div></div><div lang="en" class="section" title="1.7.&nbsp;Avoid strong databinding"><div class="titlepage"><div><div><h3 class="title" id="compiling-xml-schema-avoid-strong-databinding">1.7.&nbsp;Avoid strong databinding</h3></div></div></div><p>Under some limited circumstances, a weaker databinding is preferable
    for various reasons. JAXB does offer a few ways for you to achieve
    this.</p><div class="section" title="1.7.1.&nbsp;Avoid mapping to enum"><div class="titlepage"><div><div><h4 class="title" id="Avoid_mapping_to_enum">1.7.1.&nbsp;Avoid mapping to enum</h4></div></div></div><p>The following customization will stop binding a simple type to a
        type-safe enum. This can be convenient when number of constants is too
        large to be an useful enum (by default, the JAXB spec won't generate
        enum with more than 256 constants, but even 100 might be too large for
        you.)</p><div class="example"><a name="d0e2066"></a><p class="title"><b>Example&nbsp;22.&nbsp;Avoid mapping one simple type</b></p><div class="example-contents"><pre class="programlisting"><span class="ReservedWord">&lt;xs:simpleType</span> <span class="Identifier">name</span>=<span class="String">"foo"</span><span class="ReservedWord">&gt;</span>
  <span class="ReservedWord">&lt;xs:annotation&gt;</span><span class="ReservedWord">&lt;xs:appinfo&gt;</span>
    <span class="ReservedWord">&lt;jaxb:typesafeEnumClass</span> <span class="Identifier">map</span>=<span class="String">"false"</span><span class="ReservedWord"> /&gt;</span>
  <span class="ReservedWord">&lt;/xs:appinfo&gt;</span><span class="ReservedWord">&lt;/xs:annotation&gt;</span>
  <span class="ReservedWord">&lt;xs:restriction</span> <span class="Identifier">base</span>=<span class="String">"xs:string"</span><span class="ReservedWord">&gt;</span>
    <span class="ReservedWord">&lt;xs:enumeration</span> <span class="Identifier">value</span>=<span class="String">"x"</span><span class="ReservedWord"> /&gt;</span>
    <span class="ReservedWord">&lt;xs:enumeration</span> <span class="Identifier">value</span>=<span class="String">"y"</span><span class="ReservedWord"> /&gt;</span>
    <span class="ReservedWord">&lt;xs:enumeration</span> <span class="Identifier">value</span>=<span class="String">"z"</span><span class="ReservedWord"> /&gt;</span>
  <span class="ReservedWord">&lt;/xs:restriction&gt;</span>
<span class="ReservedWord">&lt;/xs:simpleType&gt;</span></pre></div></div><br class="example-break"><p>To disable such type-safe enum binding altogether for the entire
        schema, use a global binding setting like this (this is actually
        telling XJC not to generate enums if a simple type has more than 0
        constants --- the net effect is no enum generation):</p><div class="example"><a name="d0e2073"></a><p class="title"><b>Example&nbsp;23.&nbsp;Avoid generating enums at all</b></p><div class="example-contents"><pre class="programlisting"><span class="ReservedWord">&lt;xs:schema</span> <span class="Identifier">...&gt;</span>
  <span class="Identifier">&lt;xs:annotation&gt;&lt;xs:appinfo&gt;</span>
    <span class="Identifier">&lt;jaxb:globalBindings</span> <span class="Identifier">typesafeEnumMaxMembers</span>=<span class="String">"0"</span><span class="ReservedWord"> /&gt;</span>
  <span class="ReservedWord">&lt;/xs:appinfo&gt;</span><span class="ReservedWord">&lt;/xs:annotation&gt;</span>
  ...
<span class="ReservedWord">&lt;/xs:schema&gt;</span></pre></div></div><br class="example-break"></div><div class="section" title="1.7.2.&nbsp;Mapping to DOM"><div class="titlepage"><div><div><h4 class="title" id="Mapping_to_DOM">1.7.2.&nbsp;Mapping to DOM</h4></div></div></div><p>The <code class="literal">&lt;jaxb:dom&gt;</code>customization allows you to map
        a certain part of the schema into a DOM tree. This customization can
        be attached to the following schema components:</p><div class="itemizedlist"><ul class="itemizedlist" type="disc"><li class="listitem"><p>Wildcards (<code class="literal">&lt;xs:any&gt;</code>)</p></li><li class="listitem"><p>Type definitions (<code class="literal">&lt;xs:complexType&gt;</code> and
                <code class="literal">&lt;xs:simpleType&gt;</code>)</p></li><li class="listitem"><p>Model groups
                (<code class="literal">&lt;xs:choice&gt;</code>,<code class="literal">&lt;xs:all&gt;</code>,<code class="literal">&lt;xs:sequence&gt;</code>)</p></li><li class="listitem"><p>Model group declarations (<code class="literal">&lt;xs:group&gt;</code>)</p></li><li class="listitem"><p>Particles</p></li><li class="listitem"><p>Element declarations (<code class="literal">&lt;xs:element&gt;</code>)</p></li></ul></div><p>In the following example, a wildcard is mapped to a DOM node.
        Each element that matches to the wildcard will be turned into a DOM
        tree.</p><div class="example"><a name="d0e2131"></a><p class="title"><b>Example&nbsp;24.&nbsp;Dom Customization example</b></p><div class="example-contents"><pre class="programlisting"><span class="ReservedWord">&lt;xs:schema</span> <span class="Identifier">xmlns:xs</span>=<span class="String">"http://www.w3.org/2001/XMLSchema"</span>
               <span class="Identifier">xmlns:jaxb</span>=<span class="String">"http://java.sun.com/xml/ns/jaxb"</span>
               <span class="Identifier">jaxb:version</span>=<span class="String">"2.0"</span><span class="ReservedWord">&gt;</span>

        <span class="ReservedWord">&lt;xs:element&gt;</span>
           <span class="ReservedWord">&lt;xs:complexType&gt;</span>
              <span class="ReservedWord">&lt;xs:sequence&gt;</span>
                 <span class="ReservedWord">&lt;xs:any</span> <span class="Identifier">maxOccurs</span>=<span class="String">"unbounded"</span> <span class="Identifier">processContents</span>=<span class="String">"skip"</span><span class="ReservedWord">&gt;</span>
                    <span class="ReservedWord">&lt;xs:annotation&gt;</span><span class="ReservedWord">&lt;xs:appinfo&gt;</span>
                      <span class="ReservedWord">&lt;jaxb:dom/&gt;</span>
                    <span class="ReservedWord">&lt;/xs:appinfo&gt;</span><span class="ReservedWord">&lt;/xs:annotation&gt;</span>
                 <span class="ReservedWord">&lt;/xs:any&gt;</span>
              <span class="ReservedWord">&lt;/xs:sequence&gt;</span>
           <span class="ReservedWord">&lt;/xs:complexType&gt;</span>
        <span class="ReservedWord">&lt;/xs:element&gt;</span>
    .
    .
    .
    <span class="ReservedWord">&lt;/xs:schema&gt;</span></pre></div></div><br class="example-break"><p>This extension can be used to access wildcard content or can be
        used to process a part of a document by using other technologies that
        require "raw" XML. By default, JAXB generates a <code class="code">getContent()</code> method
        for accessing wildcard content, but it only supports "lax" handling
        which means that unknown content is discarded. You may find more
        information in 7.12 chapter of <a class="link" href="http://www.jcp.org/en/jsr/detail?id=222" target="_top">JAXB 2
        specification</a>.</p></div></div><div lang="en" class="section" title="1.8.&nbsp;Working with generated code in memory"><div class="titlepage"><div><div><h3 class="title" id="compiling-xml-schema-working-with-generated-code-in-memory">1.8.&nbsp;Working with generated code in memory</h3></div></div></div><div class="section" title="1.8.1.&nbsp;Cloning"><div class="titlepage"><div><div><h4 class="title" id="Cloning">1.8.1.&nbsp;Cloning</h4></div></div></div><p>The generated beans (and in particular the
        <code class="literal">JAXBElement</code> class) do not support the clone operation.
        There was <a class="link" href="http://www.nabble.com/cloning-of-extended-JAXB-elements-tf3976065.html" target="_top">a
        suggestion</a> by another user that <a class="link" href="http://beanlib.sourceforge.net/" target="_top">beanlib</a> has been
        used successfully to clone JAXB objects.</p></div></div></div><div lang="en" class="section" title="2.&nbsp;Customization of Schema Compilation"><div class="titlepage"><div><div><h2 class="title" style="clear: both" id="customization-of-schema-compilation">2.&nbsp;Customization of Schema Compilation</h2></div></div></div><div lang="en" class="section" title="2.1.&nbsp;Customizing Java packages"><div class="titlepage"><div><div><h3 class="title" id="customization-of-schema-compilation-customizing-java-packages">2.1.&nbsp;Customizing Java packages</h3></div></div></div><p>The JAXB specification provides a <code class="literal">&lt;jaxb:schemaBindings&gt;</code>
    customization so that you can control which namespace goes to which
    package. See the example below:</p><div class="example"><a name="d0e2175"></a><p class="title"><b>Example&nbsp;25.&nbsp;package customization</b></p><div class="example-contents"><pre class="programlisting">    <span class="ReservedWord">&lt;jaxb:schemaBindings&gt;</span>
      <span class="ReservedWord">&lt;jaxb:package</span> <span class="Identifier">name</span>=<span class="String">"org.acme.foo"</span><span class="ReservedWord">/&gt;</span>
    <span class="ReservedWord">&lt;/jaxb:schemaBindings&gt;</span></pre></div></div><br class="example-break"><p>You can do this as an internal customization (in which case you put
    this in <code class="literal">&lt;xs:annotation&gt;</code><code class="literal">&lt;xs:appinfo&gt;</code> under place it right under
    the <code class="literal">&lt;xs:schema&gt;</code> element), or do this as an external customization,
    like this:</p><div class="example"><a name="d0e2190"></a><p class="title"><b>Example&nbsp;26.&nbsp;External package customization</b></p><div class="example-contents"><pre class="programlisting"><span class="ReservedWord">&lt;bindings</span> <span class="Identifier">xmlns</span>=<span class="String">"http://java.sun.com/xml/ns/jaxb"</span> <span class="Identifier">version</span>=<span class="String">"2.1"</span><span class="ReservedWord">&gt;</span>
  <span class="ReservedWord">&lt;bindings</span> <span class="Identifier">schemaLocation</span>=<span class="String">"../path/to/my.xsd"</span><span class="ReservedWord">&gt;</span>
    <span class="ReservedWord">&lt;schemaBindings&gt;</span>
      <span class="ReservedWord">&lt;package</span> <span class="Identifier">name</span>=<span class="String">"org.acme.foo"</span><span class="ReservedWord">/&gt;</span>
    <span class="ReservedWord">&lt;/schemaBindings&gt;</span>
  <span class="ReservedWord">&lt;/bindings&gt;</span>
<span class="ReservedWord">&lt;/bindings&gt;</span></pre></div></div><br class="example-break"><p>Note that this customization is per namespace. That is, even if your
    schema is split into multiple schema documents, you cannot put them into
    different packages if they are all in the same namespace.</p><div class="section" title="2.1.1.&nbsp;Tip: get rid of the org.w3._2001.xmlschema package"><div class="titlepage"><div><div><h4 class="title" id="Tip__get_rid_of_the_org_w3__2001_xmlschema_package">2.1.1.&nbsp;Tip: get rid of the org.w3._2001.xmlschema package</h4></div></div></div><p>Under some rare circumstances, XJC will generate some Java
        classes into a package called <code class="literal">org.w3._2001.xmlschema</code>.
        This happens when XJC decides that it needs some Java artifacts for
        the XML Schema built-in namespace of
        <code class="code">http://www.w3.org/2001/XMLSchema</code>.</p><p>Since this package name is most often problematic, you can
        rename this by simply saving the following text in an .xsd file and
        submitting it to XJC along with the other schemas you have:</p><div class="example"><a name="d0e2210"></a><p class="title"><b>Example&nbsp;27.&nbsp;Schemalet to get rid of org.w3._2001.xmlschema</b></p><div class="example-contents"><pre class="programlisting"><span class="ReservedWord">&lt;schema</span> <span class="Identifier">xmlns</span>=<span class="String">"http://www.w3.org/2001/XMLSchema"</span>
  <span class="Identifier">targetNamespace</span>=<span class="String">"http://www.w3.org/2001/XMLSchema"</span>
  <span class="Identifier">xmlns:jaxb</span>=<span class="String">"http://java.sun.com/xml/ns/jaxb"</span>
  <span class="Identifier">jaxb:version</span>=<span class="String">"2.0"</span><span class="ReservedWord">&gt;</span>
  <span class="ReservedWord">&lt;annotation&gt;</span><span class="ReservedWord">&lt;appinfo&gt;</span>
    <span class="ReservedWord">&lt;jaxb:schemaBindings&gt;</span>
      <span class="ReservedWord">&lt;jaxb:package</span> <span class="Identifier">name</span>=<span class="String">"org.acme.foo"</span><span class="ReservedWord">/&gt;</span>
    <span class="ReservedWord">&lt;/jaxb:schemaBindings&gt;</span>
  <span class="ReservedWord">&lt;/appinfo&gt;</span><span class="ReservedWord">&lt;/annotation&gt;</span>
<span class="ReservedWord">&lt;/schema&gt;</span></pre></div></div><br class="example-break"><p>This is bit tricky, but the idea is that since you can define a
        schema for one namespace in multiple schema documents, this makes XJC
        think that this schema is a part of the built-in "XML Schema for XML
        Schema".</p></div></div><div lang="en" class="section" title="2.2.&nbsp;Using SCD for customizations"><div class="titlepage"><div><div><h3 class="title" id="customization-of-schema-compilation-using-scd-for-customizations">2.2.&nbsp;Using SCD for customizations</h3></div></div></div><p>When using an external customization file, the JAXB spec requires
    that you use XPath as a means to specify what your customization is
    attached to. For example, if you want to change the class name generated
    from a complex type, you'd write something like:</p><div class="example"><a name="d0e2223"></a><p class="title"><b>Example&nbsp;28.&nbsp;External customization example</b></p><div class="example-contents"><pre class="programlisting"><span class="ReservedWord">&lt;bindings</span> <span class="Identifier">xmlns</span>=<span class="String">"http://java.sun.com/xml/ns/jaxb"</span> <span class="Identifier">version</span>=<span class="String">"2.0"</span> <span class="Identifier">xmlns:xs</span>=<span class="String">"http://www.w3.org/2001/XMLSchema"</span><span class="ReservedWord">&gt;</span>
  <span class="ReservedWord">&lt;bindings</span> <span class="Identifier">schemaLocation</span>=<span class="String">"../path/to/my.xsd"</span> <span class="Identifier">node</span>=<span class="String">"/xs:schema/xs:complexType[@name='foo']"</span><span class="ReservedWord">&gt;</span>
    <span class="ReservedWord">&lt;class</span> <span class="Identifier">name</span>=<span class="String">"FooType"</span><span class="ReservedWord">/&gt;</span>
  <span class="ReservedWord">&lt;/bindings&gt;</span>
<span class="ReservedWord">&lt;/bindings&gt;</span></pre></div></div><br class="example-break"><p>While the above process works, the problem with this is that the
    XPath+ <code class="literal">schemaLocation</code> combo tends to be verbose and error
    prone. It's verbose, because often a trivial target schema component like
    this "global complex type foo" takes up a lot of characters. The xs
    namespace declaration also takes up some space, although in this case we
    managed to avoid declaring the "tns" namespace (that represents the
    namespace that the schema defines.)</p><p>It's also error prone, because it relies on the way schema documents
    are laid out, because the schemaLocation attribute needs to point to the
    right schema document file. When a schema is split into multiple files for
    modularity (happens especially often with large schemas), then you'd have
    to find which schema file it is. Even though you can use relative paths,
    this hard-coding of path information makes it hard to pass around the
    binding file to other people.</p><p>JAXB RI 2.1 and onward offers a better way to do this as a vendor
    extension.</p><p>The key technology to solve this problem is a <a class="link" href="http://www.w3.org/TR/xmlschema-ref/" target="_top">"<code class="literal">schema component
    designator</code>"</a> (SCD.) This is a path language just like XPath, but
    whereas XPath is designed to refer to XML infoset items like elements and
    attributes, SCD is designed to refer to schema components like element
    declarations or complex types.</p><p>With SCD, the above binding can be written more concisely as
    follows:</p><div class="example"><a name="d0e2247"></a><p class="title"><b>Example&nbsp;29.&nbsp;External customization by SCD</b></p><div class="example-contents"><pre class="programlisting"><span class="ReservedWord">&lt;bindings</span> <span class="Identifier">xmlns</span>=<span class="String">"http://java.sun.com/xml/ns/jaxb"</span> <span class="Identifier">version</span>=<span class="String">"2.1"</span> <span class="Identifier">xmlns:tns</span>=<span class="String">"http://my.namespace/"</span><span class="ReservedWord">&gt;</span>
  <span class="ReservedWord">&lt;bindings</span> <span class="Identifier">scd</span>=<span class="String">"/type::tns:foo"</span><span class="ReservedWord">&gt;</span>
    <span class="ReservedWord">&lt;class</span> <span class="Identifier">name</span>=<span class="String">"FooType"</span><span class="ReservedWord">/&gt;</span>
  <span class="ReservedWord">&lt;/bindings&gt;</span>
<span class="ReservedWord">&lt;/bindings&gt;</span></pre></div></div><br class="example-break"><p><code class="code">/type::tns:foo</code> can be written more concisely as
    <code class="code">/~tns:foo</code>, too. If you are interested in more about the
    syntax of SCDs, read <a class="link" href="http://www.w3.org/TR/xmlschema-ref/#section-path-examples" target="_top">the
    example part of the spec</a>, and maybe <a class="link" href="http://www.w3.org/TR/xmlschema-ref/#section-path-ebnf" target="_top">EBNF</a>.
    If you know XPath, I think you'll find this fairly easy to learn.</p><p>Another benefit of an SCD is that tools will have easier time
    generating SCDs than XPath, as XPaths are often vulnerable to small
    changes in the schema document, while SCDs are much more robust. The
    downside of using SCD is as of JAXB 2.1, this feature is a vendor
    extension and not defined in the spec.</p></div><div lang="en" class="section" title="2.3.&nbsp;Using different datatypes"><div class="titlepage"><div><div><h3 class="title" id="customization-of-schema-compilation-using-different-datatypes">2.3.&nbsp;Using different datatypes</h3></div></div></div><p>JAXB has a built-in table that determines what Java classes are used
    to represent what XML Schema built-in types, but this can be
    customized.</p><p>One of the common use cases for customization is to replace the
    <code class="literal">XMLGregorianCalendar</code> with the friendlier
    <code class="literal">Calendar</code> or <code class="literal">Date</code>.
    <code class="literal">XMLGregorianCalendar</code> is designed to be 100% compatible with
    XML Schema's date/time system, such as providing infinite precision in
    sub-seconds and years, but often the ease of use of those familiar Java
    classes win over the precise compatibility.</p><p>One very easy way to do this is to simply use your IDE (or even
    "<code class="literal">sed</code>") to replace all the references to <code class="literal">XMLGregorianCalendar</code>
    by <code class="literal">Calendar</code>. This is of course not a very attractive option
    if your build process runs XJC as a part of it.</p><p>Alternatively, the following customization file can be used to do
    this. When using external customization file, the JAXB spec requires you
    to use XPath as a means to specify what your customization is attached to.
    For example, if you want to change the class name generated from a complex
    type, you'd use the following customization:</p><div class="example"><a name="d0e2300"></a><p class="title"><b>Example&nbsp;30.&nbsp;Customization to use Calendar for x<code class="literal">s:date</code></b></p><div class="example-contents"><pre class="programlisting"><span class="ReservedWord">&lt;bindings</span> <span class="Identifier">xmlns</span>=<span class="String">"http://java.sun.com/xml/ns/jaxb"</span> <span class="Identifier">version</span>=<span class="String">"2.0"</span> <span class="Identifier">xmlns:xs</span>=<span class="String">"http://www.w3.org/2001/XMLSchema"</span><span class="ReservedWord">&gt;</span>
  <span class="ReservedWord">&lt;globalBindings&gt;</span>
    <span class="ReservedWord">&lt;javaType</span> <span class="Identifier">name</span>=<span class="String">"java.util.Calendar"</span> <span class="Identifier">xmlType</span>=<span class="String">"xs:date"</span>
      <span class="Identifier">parseMethod</span>=<span class="String">"javax.xml.bind.DatatypeConverter.parseDate"</span>
      <span class="Identifier">printMethod</span>=<span class="String">"javax.xml.bind.DatatypeConverter.printDate"</span><span class="ReservedWord">
    /&gt;</span>
  <span class="ReservedWord">&lt;/globalBindings&gt;</span>
<span class="ReservedWord">&lt;/bindings&gt;</span></pre></div></div><br class="example-break"><p>Save this in a file and specify this to JAXB with the "-b"
    option.</p><p>To use the <code class="literal">Date</code> class, you'll need to do a bit more
    work. First, put the following class into your source tree:</p><div class="example"><a name="d0e2314"></a><p class="title"><b>Example&nbsp;31.&nbsp;Adapter for Date</b></p><div class="example-contents"><pre class="programlisting"><span class="ReservedWord">package</span> org.acme.foo;
<span class="ReservedWord">public</span> <span class="ReservedWord">class</span> DateAdapter {
  <span class="ReservedWord">public</span> <span class="ReservedWord">static</span> Date parseDate(String s) {
    <span class="ReservedWord">return</span> DatatypeConverter.parseDate(s).getTime();
  }
  <span class="ReservedWord">public</span> <span class="ReservedWord">static</span> String printDate(Date dt) {
    Calendar cal = <span class="ReservedWord">new</span> GregorianCalendar();
    cal.setTime(dt);
    <span class="ReservedWord">return</span> DatatypeConverter.printDate(cal);
  }
}</pre></div></div><br class="example-break"><p>... then your binding file will be the following:</p><div class="example"><a name="d0e2321"></a><p class="title"><b>Example&nbsp;32.&nbsp;Customization to use Date for x<code class="literal">s:date</code></b></p><div class="example-contents"><pre class="programlisting"><span class="ReservedWord">&lt;bindings</span> <span class="Identifier">xmlns</span>=<span class="String">"http://java.sun.com/xml/ns/jaxb"</span> <span class="Identifier">version</span>=<span class="String">"2.0"</span> <span class="Identifier">xmlns:xs</span>=<span class="String">"http://www.w3.org/2001/XMLSchema"</span><span class="ReservedWord">&gt;</span>
  <span class="ReservedWord">&lt;globalBindings&gt;</span>
    <span class="ReservedWord">&lt;javaType</span> <span class="Identifier">name</span>=<span class="String">"java.util.Date"</span> <span class="Identifier">xmlType</span>=<span class="String">"xs:date"</span>
      <span class="Identifier">parseMethod</span>=<span class="String">"org.acme.foo.DateAadpter.parseDate"</span>
      <span class="Identifier">printMethod</span>=<span class="String">"org.acme.foo.DateAdapter.printDate"</span><span class="ReservedWord">
    /&gt;</span>
  <span class="ReservedWord">&lt;/globalBindings&gt;</span>
<span class="ReservedWord">&lt;/bindings&gt;</span></pre></div></div><br class="example-break"><p>If you are using JAXB 2.0, and not 2.1, see <a class="link" href="http://weblogs.java.net/blog/kohsuke/archive/2006/03/how_do_i_map_xs.html" target="_top">this
    blog entry</a> for how to do this for 2.0.</p></div></div><div lang="en" class="section" title="3.&nbsp;Annotating Your Classes"><div class="titlepage"><div><div><h2 class="title" style="clear: both" id="annotating-your-classes">3.&nbsp;Annotating Your Classes</h2></div></div></div><div lang="en" class="section" title="3.1.&nbsp;Mapping your favorite class"><div class="titlepage"><div><div><h3 class="title" id="annotating-your-classes-mapping-your-favorite-class">3.1.&nbsp;Mapping your favorite class</h3></div></div></div><div class="section" title="3.1.1.&nbsp;ResultSet"><div class="titlepage"><div><div><h4 class="title" id="ResultSet">3.1.1.&nbsp;ResultSet</h4></div></div></div><p>JAXB (or any other databinding engine, for that matter) is for
        binding strongly-typed POJO-like objects to XML, such as
        <code class="literal">AddressBook</code> class, <code class="literal">PurchaseOrder</code> class, and
        so on, where you have fields and methods that shape a class.</p><p>There are other kinds of classes that are more close to
        reflection. Those classes don't have methods like
        <code class="literal">getAddress</code>, and instead you'd do
        <code class="code">get("Address")</code>. JDBC ResultSet is one of those classes.
        It's one class that represents million different data structures, be
        it a customer table or a product table. Generally speaking, these
        classes does not allow JAXB to statically determine what the XML
        representation should look like. Instead, you almost always need to
        look at an instance to determine the shape of XML.</p><p>These classes are not really suitable for binding in JAXB. If
        this is the only object that you'd want to write out, then you'd be
        better off using XMLStreamWriter or some such XML infoset writing API.
        There are <a class="link" href="http://www.google.com/search?q=ResultSet+XML" target="_top">a few online
        articles</a> that cover this topic. Also, many modern database
        offers a native ability to export a query into XML, which is supposed
        to work a lot faster than you'd do in Java (and saves your time of
        writing code.)</p><p>If you are using ResultSet as a part of your object tree that
        you want to marshal to JAXB, then you can use
        <code class="literal">XmlJavaTypeAdapter</code>.</p></div><div class="section" title="3.1.2.&nbsp;HashMap"><div class="titlepage"><div><div><h4 class="title" id="HashMap">3.1.2.&nbsp;HashMap</h4></div></div></div><p>JAXB spec defines a special handling for <code class="literal">Map</code> when
        it's used as a propety of a bean. For example, the following bean
        would produce XMLs like the following:</p><div class="example"><a name="d0e2378"></a><p class="title"><b>Example&nbsp;33.&nbsp;Bean with Map</b></p><div class="example-contents"><pre class="programlisting"><span class="Annotation">@XmlRootElement</span>
<span class="ReservedWord">class</span> Foo {
  <span class="ReservedWord">public</span> HashMap&lt;String,Integer&gt; map;
}</pre></div></div><br class="example-break"><div class="example"><a name="d0e2383"></a><p class="title"><b>Example&nbsp;34.&nbsp;XML representation</b></p><div class="example-contents"><pre class="programlisting"><span class="ReservedWord">&lt;foo&gt;</span>
  <span class="ReservedWord">&lt;map&gt;</span>
    <span class="ReservedWord">&lt;entry&gt;</span>
      <span class="ReservedWord">&lt;key&gt;</span>a<span class="ReservedWord">&lt;/key&gt;</span>
      <span class="ReservedWord">&lt;value&gt;</span>1<span class="ReservedWord">&lt;/value&gt;</span>
    <span class="ReservedWord">&lt;/entry&gt;</span>
    <span class="ReservedWord">&lt;entry&gt;</span>
      <span class="ReservedWord">&lt;key&gt;</span>b<span class="ReservedWord">&lt;/key&gt;</span>
      <span class="ReservedWord">&lt;value&gt;</span>2<span class="ReservedWord">&lt;/value&gt;</span>
    <span class="ReservedWord">&lt;/entry&gt;</span>
  <span class="ReservedWord">&lt;/map&gt;</span>
<span class="ReservedWord">&lt;/foo&gt;</span></pre></div></div><br class="example-break"><p>Unfortunately, as of 2.1, this processing is only defined for
        bean properties and not when you marshal <code class="literal">HashMap</code> as a
        top-level object (such as a value in <code class="literal">JAXBElement</code>.) In
        such case, <code class="literal">HashMap</code> will be treated as a Java bean, and
        when you look at <code class="literal">HashMap</code> as a bean it defines no
        getter/setter property pair, so the following code would produce the
        following XML:</p><div class="example"><a name="d0e2402"></a><p class="title"><b>Example&nbsp;35.&nbsp;Bean with Map</b></p><div class="example-contents"><pre class="programlisting">m = <span class="ReservedWord">new</span> HashMap();
m.put(<span class="String">"abc"</span>,<span class="Numeric">1</span>);
marshaller.marshal(<span class="ReservedWord">new</span> JAXBElement(<span class="ReservedWord">new</span> QName(<span class="String">"root"</span>),HashMap.<span class="ReservedWord">class</span>,m),System.out);</pre></div></div><br class="example-break"><div class="example"><a name="d0e2407"></a><p class="title"><b>Example&nbsp;36.&nbsp;XML representation</b></p><div class="example-contents"><pre class="programlisting"><span class="ReservedWord">&lt;root /&gt;</span></pre></div></div><br class="example-break"><p>This issue has been recorded as <a class="link" href="http://jaxb.java.net/issues/show_bug.cgi?id=223" target="_top">#223</a>
        and the fix needs to happen in later versions of the JAXB spec.</p><p>In the mean time, such top-level objects have to be first
        adapted to a bean that JAXB can process. This has added benefit of
        being able to control XML representation better. The following code
        illustrates how to do this:</p><div class="example"><a name="d0e2419"></a><p class="title"><b>Example&nbsp;37.&nbsp;Adapting HashMap</b></p><div class="example-contents"><pre class="programlisting"><span class="ReservedWord">public</span> <span class="ReservedWord">class</span> MyHashMapType {
    <span class="ReservedWord">public</span> List&lt;MyHashMapEntryType&gt; entry = <span class="ReservedWord">new</span> ArrayList&lt;MyHashMapEntryType&gt;();
    <span class="ReservedWord">public</span> MyHashMapType(Map&lt;String,Integer&gt; map) {
        <span class="ReservedWord">for</span>( Map.Entry&lt;String,Integer&gt; e : map.entrySet() )
            entry.add(<span class="ReservedWord">new</span> MyHashMapEntryType(e));
    }
    <span class="ReservedWord">public</span> MyHashMapType() {}
}

<span class="ReservedWord">public</span> <span class="ReservedWord">class</span> MyHashMapEntryType {
    <span class="Annotation">@XmlAttribute</span> <span class="Comment">// @XmlElement and @XmlValue are also fine</span>
    <span class="ReservedWord">public</span> String key;

    <span class="Annotation">@XmlAttribute</span> <span class="Comment">// @XmlElement and @XmlValue are also fine</span>
    <span class="ReservedWord">public</span> <span class="ReservedWord">int</span> value;

    <span class="ReservedWord">public</span> MyHashMapEntryType() {}
    <span class="ReservedWord">public</span> MyHashMapEntryType(Map.Entry&lt;String,Integer&gt; e) {
       key = e.getKey();
       value = e.getValue();
    }
}

marshaller.marshal(<span class="ReservedWord">new</span> JAXBElement(<span class="ReservedWord">new</span> QName(<span class="String">"root"</span>),MyHashMapType.<span class="ReservedWord">class</span>,<span class="ReservedWord">new</span> MyHashMapType(m)),System.out);</pre></div></div><br class="example-break"><p>If you have a lot of difference kinds of <code class="literal">Map</code>, you
        can instead use <code class="literal">Object</code> as the key and the value type. In
        that way, you'll be able to use maps with different type parameters,
        at the expense of seeing <code class="literal">xsi:type</code> attribute on the
        instance document.</p></div></div><div lang="en" class="section" title="3.2.&nbsp;Mapping interfaces"><div class="titlepage"><div><div><h3 class="title" id="annotating-your-classes-mapping-interfaces">3.2.&nbsp;Mapping interfaces</h3></div></div></div><p>Because of the difference between the XML type system induced by W3C
    XML Schema and the Java type system, JAXB cannot bind interfaces out of
    the box, but there are a few things you can do.</p><div class="section" title="3.2.1.&nbsp;Use @XmlRootElement"><div class="titlepage"><div><div><h4 class="title" id="Use__XmlRootElement">3.2.1.&nbsp;Use <code class="literal">@XmlRootElement</code></h4></div></div></div><p>When your interface is implemented by a large number of
        sub-classes, consider using <a class="link" href="http://jaxb.java.net/nonav/jaxb20-fcs/docs/api/index.html?javax/xml/bind/annotation//3.2.1XmlRootElement.html" target="_top"><code class="literal">XmlRootElement</code></a> annotation like this:</p><div class="example"><a name="d0e2452"></a><p class="title"><b>Example&nbsp;38.&nbsp;XmlRootElement for open-ended interfaces</b></p><div class="example-contents"><pre class="programlisting"><span class="Annotation">@XmlRootElement</span>
<span class="ReservedWord">class</span> Zoo {
  <span class="Annotation">@XmlAnyElement</span>
  <span class="ReservedWord">public</span> List&lt;Animal&gt; animals;
}

<span class="ReservedWord">interface</span> Animal {
  <span class="ReservedWord">void</span> sleep();
  <span class="ReservedWord">void</span> eat();
  ...
}

<span class="Annotation">@XmlRootElement</span>
<span class="ReservedWord">class</span> Dog <span class="ReservedWord">implements</span> Animal { ... }

<span class="Annotation">@XmlRootElement</span>
<span class="ReservedWord">class</span> Lion <span class="ReservedWord">implements</span> Animal { ... }</pre></div></div><br class="example-break"><p>This will produce XML documents like this:</p><div class="example"><a name="d0e2459"></a><p class="title"><b>Example&nbsp;39.&nbsp;XML for XmlRootElement</b></p><div class="example-contents"><pre class="programlisting"><span class="ReservedWord">&lt;zoo&gt;</span>
    <span class="ReservedWord">&lt;lion&gt;</span> ... <span class="ReservedWord">&lt;/lion&gt;</span>
    <span class="ReservedWord">&lt;dog&gt;</span> ... <span class="ReservedWord">&lt;/dog&gt;</span>
<span class="ReservedWord">&lt;/zoo&gt;</span></pre></div></div><br class="example-break"><p>The key characteristics of this approach is:</p><div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem"><p>Implementations are open-ended; anyone can implement
                those interfaces, even by different people from different
                modules, provided they are all given to the
                <code class="literal">JAXBContext.newInstance</code> method. There's no need
                to list all the implementation classes in anywhere.</p></li><li class="listitem"><p>Each implementation of the interface needs to have an
                unique element name.</p></li><li class="listitem"><p>Every reference to interface needs to have the <a class="link" href="http://jaxb.java.net/nonav/jaxb20-fcs/docs/api/index.html?javax/xml/bind/annotation//3.2.1XmlElementRef.html" target="_top"><code class="literal">XmlElementRef</code></a> annotation. The
                <code class="code">type=Object.class</code> portion tells JAXB that the
                greatest common base type of all implementations would be
                <code class="literal">java.lang.Object</code>.</p></li></ol></div><p><code class="literal">@XmlElementWrapper</code> is often useful with this,
        as it allows you need to group them. Such as:</p><div class="example"><a name="d0e2493"></a><p class="title"><b>Example&nbsp;40.&nbsp;XmlRootElement for open-ended interfaces</b></p><div class="example-contents"><pre class="programlisting"><span class="Annotation">@XmlRootElement</span>
<span class="ReservedWord">class</span> Zoo {
  <span class="Annotation">@XmlElementWrapper</span>
  <span class="Annotation">@XmlAnyElement</span>
  <span class="ReservedWord">public</span> List&lt;Animal&gt; onExhibit;
  <span class="Annotation">@XmlElementWrapper</span>
  <span class="Annotation">@XmlAnyElement</span>
  <span class="ReservedWord">public</span> List&lt;Animal&gt; resting;
}</pre></div></div><br class="example-break"><div class="example"><a name="d0e2498"></a><p class="title"><b>Example&nbsp;41.&nbsp;Effect of XmlElementWrapper</b></p><div class="example-contents"><pre class="programlisting"><span class="ReservedWord">&lt;zoo&gt;</span>
    <span class="ReservedWord">&lt;onExhibit&gt;</span>
        <span class="ReservedWord">&lt;lion&gt;</span> ... <span class="ReservedWord">&lt;/lion&gt;</span>
        <span class="ReservedWord">&lt;dog&gt;</span> ... <span class="ReservedWord">&lt;/dog&gt;</span>
    <span class="ReservedWord">&lt;/onExhibit&gt;</span>
    <span class="ReservedWord">&lt;resting&gt;</span>
        <span class="ReservedWord">&lt;lion&gt;</span> ... <span class="ReservedWord">&lt;/lion&gt;</span>
        <span class="ReservedWord">&lt;dog&gt;</span> ... <span class="ReservedWord">&lt;/dog&gt;</span>
    <span class="ReservedWord">&lt;/resting&gt;</span>
<span class="ReservedWord">&lt;/zoo&gt;</span></pre></div></div><br class="example-break"></div><div class="section" title="3.2.2.&nbsp;Use @XmlJavaTypeAdapter"><div class="titlepage"><div><div><h4 class="title" id="Use__XmlJavaTypeAdapter">3.2.2.&nbsp;Use <code class="literal">@XmlJavaTypeAdapter</code></h4></div></div></div><p>When you use interfaces just to hide your implementation classes
        from exposure, and when there's 1-to-1 (or close to 1-on-1)
        relationship between a class and an interface, <a class="link" href="http://jaxb.java.net/nonav/jaxb20-fcs/docs/api/index.html?javax/xml/bind/annotation//adapters/XmlJavaTypeAdapter.html" target="_top"><code class="literal">XmlJavaTypeAdapter</code></a> can be used like below.</p><div class="example"><a name="d0e2514"></a><p class="title"><b>Example&nbsp;42.&nbsp;XmlJavaTypeAdapter for interfaces</b></p><div class="example-contents"><pre class="programlisting"><span class="Annotation">@XmlJavaTypeAdapter(FooImpl.Adapter.class)</span>
<span class="ReservedWord">interface</span> IFoo {
  ...
}
<span class="ReservedWord">class</span> FooImpl <span class="ReservedWord">implements</span> IFoo {
  <span class="Annotation">@XmlAttribute</span>
  <span class="ReservedWord">private</span> String name;
  <span class="Annotation">@XmlElement</span>
  <span class="ReservedWord">private</span> <span class="ReservedWord">int</span> x;

  ...

  <span class="ReservedWord">static</span> <span class="ReservedWord">class</span> Adapter <span class="ReservedWord">extends</span> XmlAdapter&lt;FooImpl,IFoo&gt; {
    IFoo unmarshal(FooImpl v) { <span class="ReservedWord">return</span> v; }
    FooImpl marshal(IFoo v) { <span class="ReservedWord">return</span> (FooImpl)v; }
  }
}

<span class="ReservedWord">class</span> Somewhere {
  <span class="ReservedWord">public</span> IFoo lhs;
  <span class="ReservedWord">public</span> IFoo rhs;
}</pre></div></div><br class="example-break"><div class="example"><a name="d0e2519"></a><p class="title"><b>Example&nbsp;43.&nbsp;XML of XmlJavaTypeAdapter</b></p><div class="example-contents"><pre class="programlisting"><span class="ReservedWord">&lt;somewhere&gt;</span>
  <span class="ReservedWord">&lt;lhs</span> <span class="Identifier">name</span>=<span class="String">"..."</span><span class="ReservedWord">&gt;</span>
    <span class="ReservedWord">&lt;x&gt;</span>5<span class="ReservedWord">&lt;/x&gt;</span>
  <span class="ReservedWord">&lt;/lhs&gt;</span>
  <span class="ReservedWord">&lt;rhs</span> <span class="Identifier">name</span>=<span class="String">"..."</span><span class="ReservedWord">&gt;</span>
    <span class="ReservedWord">&lt;x&gt;</span>5<span class="ReservedWord">&lt;/x&gt;</span>
  <span class="ReservedWord">&lt;/rhs&gt;</span>
<span class="ReservedWord">&lt;/somewhere&gt;</span></pre></div></div><br class="example-break"><p>The key characteristics of this approach is:</p><div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem"><p>Interface and implementation will be tightly coupled
                through an adapter, although changing an adapter code will
                allow you to support multiple implementations.</p></li><li class="listitem"><p>There's no need of any annotation in where interfaces
                are used.</p></li></ol></div><p>A variation of this technique is when you have a few
        implementations for interface, not just one.</p><div class="example"><a name="d0e2535"></a><p class="title"><b>Example&nbsp;44.&nbsp;XmlJavaTypeAdapter for interfaces with multiple
            implementations</b></p><div class="example-contents"><pre class="programlisting"><span class="Annotation">@XmlJavaTypeAdapter(AbstractFooImpl.Adapter.class)</span>
<span class="ReservedWord">interface</span> IFoo {
  ...
}
<span class="ReservedWord">abstract</span> <span class="ReservedWord">class</span> AbstractFooImpl <span class="ReservedWord">implements</span> IFoo {
  ...

  <span class="ReservedWord">static</span> <span class="ReservedWord">class</span> Adapter <span class="ReservedWord">extends</span> XmlAdapter&lt;AbstractFooImpl,IFoo&gt; {
    IFoo unmarshal(AbstractFooImpl v) { <span class="ReservedWord">return</span> v; }
    AbstractFooImpl marshal(IFoo v) { <span class="ReservedWord">return</span> (AbstractFooImpl)v; }
  }
}

<span class="ReservedWord">class</span> SomeFooImpl <span class="ReservedWord">extends</span> AbstractFooImpl {
  <span class="Annotation">@XmlAttribute</span> String name;
  ...
}

<span class="ReservedWord">class</span> AnotherFooImpl <span class="ReservedWord">extends</span> AbstractFooImpl {
  <span class="Annotation">@XmlAttribute</span> <span class="ReservedWord">int</span> id;
  ...
}

<span class="ReservedWord">class</span> Somewhere {
  <span class="ReservedWord">public</span> IFoo lhs;
  <span class="ReservedWord">public</span> IFoo rhs;
}</pre></div></div><br class="example-break"><div class="example"><a name="d0e2540"></a><p class="title"><b>Example&nbsp;45.&nbsp;XML of XmlJavaTypeAdapter with multiple
            implementations</b></p><div class="example-contents"><pre class="programlisting"><span class="ReservedWord">&lt;somewhere&gt;</span>
  <span class="ReservedWord">&lt;lhs</span> <span class="Identifier">xsi:type</span>=<span class="String">"someFooImpl"</span> <span class="Identifier">name</span>=<span class="String">"..."</span><span class="ReservedWord">&gt;</span>
  <span class="ReservedWord">&lt;/lhs&gt;</span>
  <span class="ReservedWord">&lt;rhs</span> <span class="Identifier">xsi:type</span>=<span class="String">"anotherFooImpl"</span> <span class="Identifier">id</span>=<span class="String">"3"</span><span class="ReservedWord"> /&gt;</span>
<span class="ReservedWord">&lt;/somewhere&gt;</span></pre></div></div><br class="example-break"><p>Note that <code class="literal">SomeFooImpl</code> and
        <code class="literal">AnotherFooImpl</code> must be submitted to
        <code class="literal">JAXBContext.newInstance</code> one way or the other.</p><p>To take this example a bit further, you can use
        <code class="literal">Object</code> instead of <code class="literal">AbstractFooImpl</code>. The
        following example illustarates this:</p><div class="example"><a name="d0e2564"></a><p class="title"><b>Example&nbsp;46.&nbsp;XmlJavaTypeAdapter for interfaces with multiple
            implementations</b></p><div class="example-contents"><pre class="programlisting"><span class="Annotation">@XmlJavaTypeAdapter(AnyTypeAdapter.class)</span>
<span class="ReservedWord">interface</span> IFoo {
  ...
}
<span class="ReservedWord">public</span> <span class="ReservedWord">class</span> AnyTypeAdapter <span class="ReservedWord">extends</span> XmlAdapter&lt;Object,Object&gt; {
  Object unmarshal(Object v) { <span class="ReservedWord">return</span> v; }
  Object marshal(Object v) { <span class="ReservedWord">return</span> v; }
}

<span class="ReservedWord">class</span> SomeFooImpl <span class="ReservedWord">implements</span> IFoo {
  <span class="Annotation">@XmlAttribute</span> String name;
  ...
}

<span class="ReservedWord">class</span> Somewhere {
  <span class="ReservedWord">public</span> IFoo lhs;
  <span class="ReservedWord">public</span> IFoo rhs;
}</pre></div></div><br class="example-break"><div class="example"><a name="d0e2569"></a><p class="title"><b>Example&nbsp;47.&nbsp;Corresponding schema</b></p><div class="example-contents"><pre class="programlisting"><span class="ReservedWord">&lt;xs:complexType</span> <span class="Identifier">name</span>=<span class="String">"somewhere"</span><span class="ReservedWord">&gt;</span>
  <span class="ReservedWord">&lt;xs:sequence&gt;</span>
    <span class="ReservedWord">&lt;xs:element</span> <span class="Identifier">name</span>=<span class="String">"lhs"</span> <span class="Identifier">type</span>=<span class="String">"xs:anyType"</span> <span class="Identifier">minOccurs</span>=<span class="String">"0"</span><span class="ReservedWord">/&gt;</span>
    <span class="ReservedWord">&lt;xs:element</span> <span class="Identifier">name</span>=<span class="String">"rhs"</span> <span class="Identifier">type</span>=<span class="String">"xs:anyType"</span> <span class="Identifier">minOccurs</span>=<span class="String">"0"</span><span class="ReservedWord">/&gt;</span>
  <span class="ReservedWord">&lt;/xs:sequence&gt;</span>
<span class="ReservedWord">&lt;/xs:complexType&gt;</span></pre></div></div><br class="example-break"><p>As you can see, the schema will generated to accept
        <code class="literal">xs:anyType</code> which is more relaxed than what the Java code
        actually demands. The instance will be the same as the above example.
        Starting from JAXB RI 2.1, we bundle the
        <code class="literal">com.sun.xml.bind.AnyTypeAdapter</code> class in the runtime that
        defines this adapter. So you won't have to write this adapter in your
        code.</p></div><div class="section" title="3.2.3.&nbsp;Use @XmlElement"><div class="titlepage"><div><div><h4 class="title" id="Use__XmlElement">3.2.3.&nbsp;Use <code class="literal">@XmlElement</code></h4></div></div></div><p>If the use of interface is very little and there's 1-to-1 (or
        close to) relationship between interfaces and implementations, then
        you might find <a class="link" href="http://jaxb.java.net/nonav/jaxb20-fcs/docs/api/index.html?javax/xml/bind/annotation//3.2.3XmlElement.html" target="_top"><code class="literal">XmlElement</code></a> to be the least amount of work.</p><div class="example"><a name="d0e2593"></a><p class="title"><b>Example&nbsp;48.&nbsp;XmlElement for interfaces</b></p><div class="example-contents"><pre class="programlisting"><span class="ReservedWord">interface</span> IFoo {
  ...
}
<span class="ReservedWord">class</span> FooImpl <span class="ReservedWord">implements</span> IFoo {
  ...
}

<span class="ReservedWord">class</span> Somewhere {
  <span class="Annotation">@XmlElement(type=FooImpl.class)</span>
  <span class="ReservedWord">public</span> IFoo lhs;
}</pre></div></div><br class="example-break"><div class="example"><a name="d0e2598"></a><p class="title"><b>Example&nbsp;49.&nbsp;XML of XmlElement</b></p><div class="example-contents"><pre class="programlisting"><span class="ReservedWord">&lt;somewhere&gt;</span>
  <span class="ReservedWord">&lt;lhs&gt;</span> ... <span class="ReservedWord">&lt;/lhs&gt;</span>
<span class="ReservedWord">&lt;/somewhere&gt;</span></pre></div></div><br class="example-break"><p>This effectively tells JAXB runtime that "even though the field
        is <code class="literal">IFoo</code>, it's really just <code class="literal">FooImpl</code>.</p><p>In this approach, a reference to an interface has to have
        knowledge of the actual implementation class. So while this requires
        the least amount of typing, it probably wouldn't work very well if
        this crosses module boundaries.</p><p>Like the <a class="link" href="http://jaxb.java.net/nonav/jaxb20-fcs/docs/api/index.html?javax/xml/bind/annotation//adapters/XmlJavaTypeAdapter.html" target="_top"><code class="literal">XmlJavaTypeAdapter</code></a> approach, this can be used
        even when there are multiple implementations, provided that they share
        the common ancestor.</p><p>The extreme of this case is to specify
        <code class="literal">@XmlElement(type=Object.class)</code>.</p></div><div class="section" title="3.2.4.&nbsp;Hand-write schema"><div class="titlepage"><div><div><h4 class="title" id="Hand_write_schema">3.2.4.&nbsp;Hand-write schema</h4></div></div></div><p>Occasionally the above approaches cause the generated schema to
        become somewhat ugly, even though it does make the JAXB runtime work
        correctly. In such case you can choose not to use the generated schema
        and instead manually modify/author schemas tht better match your
        needs.</p></div><div class="section" title="3.2.5.&nbsp;Do schema-to-java"><div class="titlepage"><div><div><h4 class="title" id="Do_schema_to_java">3.2.5.&nbsp;Do schema-to-java</h4></div></div></div><p>With sufficient knowlege, one can also use <code class="literal">&lt;jaxb:class
        ref="..."/&gt;</code> annotation so that you can cause XJC to use the classes
        you already wrote. See <a class="link" href="http://forums.java.net/jive/thread.jspa?threadID=25980&amp;tstart=60" target="_top">this
        thread</a> for an example. TODO: more details and perhaps an
        example.</p></div><div class="section" title="3.2.6.&nbsp;DOESN'T WORK: Have JAXB generate interaces and swap different implementations"><div class="titlepage"><div><div><h4 class="title" id="DOESN_T_WORK__Have_JAXB_generate_interaces_and_swap_different_implementations">3.2.6.&nbsp;DOESN'T WORK: Have JAXB generate interaces and swap different
        implementations</h4></div></div></div><p><a class="link" href="http://forums.java.net/jive/thread.jspa?messageID=224433#224433" target="_top">Some
        users attempted</a> to use the "<code class="literal">generateValueClass</code>" customization
        and see if they can completely replace the generated implementations
        with other implementations. Unfortunately, this does not work.</p><p>Even with the interface/implementation mode, JAXB runtime still
        requires that the implementation classes have all the JAXB
        annotations. So just implementing interfaces is not sufficient. (This
        mode is mainly added to simplify the migration from JAXB 1.0 to JAXB
        2.0, and that's a part of the reason why things are done this
        way.)</p></div></div><div lang="en" class="section" title="3.3.&nbsp;Evolving annotated classes"><div class="titlepage"><div><div><h3 class="title" id="annotating-your-classes-evolving-annotated-classes">3.3.&nbsp;Evolving annotated classes</h3></div></div></div><p>Here is the basic problem of evolution. You got your CoolApp v1,
    which contains class Foo that has some JAXB annotations. Now you are
    working towawrd CoolApp v2, and you want to make some changes to Foo. But
    you want to do so in such a way that v1 and v2 can still talk to each
    other.</p><p>The evolution compatibility has two different aspects. One is the
    <span class="emphasis"><em>schema compatibility</em></span>, which is about the relationship
    between the v1 schema and the v2 schema. The other is about
    <span class="emphasis"><em>runtime compatibility</em></span>, which is about reading/writing
    documents between two versions.</p><div class="section" title="3.3.1.&nbsp;Runtime compatibility"><div class="titlepage"><div><div><h4 class="title" id="Runtime_compatibility">3.3.1.&nbsp;Runtime compatibility</h4></div></div></div><p>There are two directions in the runtime compatibility. One is
        whether v1 can still read what v2 write (<span class="emphasis"><em>forward
        compatible</em></span>), and the other is whether v2 can read what v1
        wrote (<span class="emphasis"><em>backward compatible</em></span>).</p></div><div class="section" title="3.3.2.&nbsp;&#34;Semi-compatible&#34;"><div class="titlepage"><div><div><h4 class="title" id="_Semi_compatible_">3.3.2.&nbsp;"<code class="literal">Semi-compatible</code>"</h4></div></div></div><p>JAXB can read XML documents that don't exactly match what's
        expected. This is the default behavior of the JAXB unmarshaller, yet
        you can change it to a more draconian behavior (TODO: pointer to the
        unmarshalling section.)</p><p>When we are talking about evolving classes, it's often
        convenient to leave it in the default behavior, as that would allow
        JAXB to nicely ignore elements/attributes newly added in v2. So we
        call it <span class="emphasis"><em>backward semi-compatible</em></span> if v2 can read
        what v1 wrote in this default unmarshalling mode, and similarly
        <span class="emphasis"><em>forward semi-compatible</em></span> if v1 can read what v2
        wrote in this default unmarshalling mode.</p><p>Technically, these are weaker than true backward/forward
        compatibility (since you can't do a draconian error detection), yet in
        practice it works just fine.</p></div><div class="section" title="3.3.3.&nbsp;Adding/removing/changing non-annotated things"><div class="titlepage"><div><div><h4 class="title" id="Adding_removing_changing_non_annotated_things">3.3.3.&nbsp;Adding/removing/changing non-annotated things</h4></div></div></div><p>You can add, remove, or change any non-annotated fields,
        methods, inner/nested types, constructors, interfaces. Those changes
        are both backward and forward compatible, as they don't cause any
        change to the XML representation.</p><p>Adding super class is backward compatible and forward
        semi-compatible. Similarly, removing super class is forward compatible
        and backward semi-compatible.</p></div><div class="section" title="3.3.4.&nbsp;Adding/removing/changing properties"><div class="titlepage"><div><div><h4 class="title" id="Adding_removing_changing_properties">3.3.4.&nbsp;Adding/removing/changing properties</h4></div></div></div><p>Adding new annotated fields or methods is backward compatible
        and forward semi-compatible. Similarly, removing them is forward
        compatible and backward semi-compatible.</p><p>Changing a property is bit more tricky.</p><div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem"><p>If you change the property name from X to Y, that would
                be the equivalent of deleting X and adding Y, so it would be
                backward and forward semi-compatible. What JAXB really cares
                is properties' XML names and not Java names, so by using the
                <code class="literal">name</code> parameter of <a class="link" href="http://jaxb.java.net/nonav/jaxb20-fcs/docs/api/index.html?javax/xml/bind/annotation//adapters/XmlJavaTypeAdapter.html" target="_top"><code class="literal">XmlElement</code></a> , <a class="link" href="http://jaxb.java.net/nonav/jaxb20-fcs/docs/api/index.html?javax/xml/bind/annotation//adapters/XmlJavaTypeAdapter.html" target="_top"><code class="literal">XmlAttribute</code></a> et al, you can change Java
                property names without affecting XML, or change XML without
                affecting Java properties. These are backward and forward
                semi-compatible. See below:</p></li><li class="listitem"><div class="example"><a name="d0e2725"></a><p class="title"><b>Example&nbsp;50.&nbsp;Changing Java without affecting XML</b></p><div class="example-contents"><pre class="programlisting"><span class="Comment">// BEFORE</span>
<span class="ReservedWord">public</span> <span class="ReservedWord">class</span> Foo {
    <span class="ReservedWord">public</span> String abc;
}
<span class="Comment">// AFTER: Java name changed, but XML remains the same</span>
<span class="ReservedWord">public</span> <span class="ReservedWord">class</span> Foo {
    <span class="Annotation">@XmlElement(name="abc")</span>
    <span class="ReservedWord">public</span> String def;
}</pre></div></div><br class="example-break"><div class="example"><a name="d0e2730"></a><p class="title"><b>Example&nbsp;51.&nbsp;Changing XML without affecting Java</b></p><div class="example-contents"><pre class="programlisting"><span class="Comment">// BEFORE</span>
<span class="ReservedWord">public</span> <span class="ReservedWord">class</span> Foo {
    <span class="ReservedWord">public</span> String abc;
}
<span class="Comment">// AFTER: no Java change, but XML will look different</span>
<span class="ReservedWord">public</span> <span class="ReservedWord">class</span> Foo {
    <span class="Annotation">@XmlElement(name="def")</span>
    <span class="ReservedWord">public</span> String abc;
}</pre></div></div><br class="example-break"></li><li class="listitem"><p>If you change a property type, generally speaking it
                will be not compatible at all. For example, you can't change
                from <code class="literal">java.util.Calendar</code> to <code class="literal">int</code> and
                expect it to work. To make it a somewhat compatible change,
                the old type and the new type has to be related. For example,
                <code class="literal">String</code> can represent all <code class="literal">int</code> values,
                so changing <code class="literal">int</code> to <code class="literal">String</code> would be a
                backward compatible and forward semi-compatible change. <a class="link" href="http://jaxb.java.net/nonav/jaxb20-fcs/docs/api/index.html?javax/xml/bind/annotation//adapters/XmlJavaTypeAdapter.html" target="_top"><code class="literal">XmlJavaTypeAdapter</code></a> allows you to make
                changes to Java without affecting XML (or vice versa.)</p></li></ol></div></div><div class="section" title="3.3.5.&nbsp;Changing class names"><div class="titlepage"><div><div><h4 class="title" id="Changing_class_names">3.3.5.&nbsp;Changing class names</h4></div></div></div><p><a class="link" href="http://jaxb.java.net/nonav/jaxb20-fcs/docs/api/index.html?javax/xml/bind/annotation//3.3.1.4XmlType.html" target="_top"><code class="literal">XmlType</code></a> and <a class="link" href="http://jaxb.java.net/nonav/jaxb20-fcs/docs/api/index.html?javax/xml/bind/annotation//3.3.1.4XmlRootElement.html" target="_top"><code class="literal">XmlRootElement</code></a> allows you to change a class name
        without affecting XML.</p><div class="example"><a name="d0e2772"></a><p class="title"><b>Example&nbsp;52.&nbsp;Changing class name without affecting XML (1)</b></p><div class="example-contents"><pre class="programlisting"><span class="Comment">// BEFORE</span>
<span class="Annotation">@XmlRootElement</span>
<span class="ReservedWord">public</span> <span class="ReservedWord">class</span> Foo { ... }

<span class="Comment">// AFTER: no XML change</span>
<span class="Annotation">@XmlRootElement(name="foo")</span>
<span class="Annotation">@XmlType(name="foo")</span>
<span class="ReservedWord">public</span> <span class="ReservedWord">class</span> Bar { ... }</pre></div></div><br class="example-break"><div class="example"><a name="d0e2777"></a><p class="title"><b>Example&nbsp;53.&nbsp;Changing class name without affecting XML (2)</b></p><div class="example-contents"><pre class="programlisting"><span class="Comment">// BEFORE</span>
<span class="ReservedWord">public</span> <span class="ReservedWord">class</span> Foo { ... }

<span class="Comment">// AFTER: no XML change</span>
<span class="Annotation">@XmlType(name="foo")</span>
<span class="ReservedWord">public</span> <span class="ReservedWord">class</span> Bar { ... }</pre></div></div><br class="example-break"></div><div class="section" title="3.3.6.&nbsp;Schema Compatibility"><div class="titlepage"><div><div><h4 class="title" id="Schema_Compatibility">3.3.6.&nbsp;Schema Compatibility</h4></div></div></div><p>TODO.</p></div></div><div lang="en" class="section" title="3.4.&nbsp;XML layout and in-memory data layout"><div class="titlepage"><div><div><h3 class="title" id="annotating-your-classes-xml-layout-and-in-memory-data-layout">3.4.&nbsp;XML layout and in-memory data layout</h3></div></div></div><p>Your program sometimes needs to have a different in-memory data
    structure from its XML representation. JAXB has a few different ways to
    achieve this.</p><div class="section" title="3.4.1.&nbsp;XmlJavaTypeAdapter"><div class="titlepage"><div><div><h4 class="title" id="XmlJavaTypeAdapter">3.4.1.&nbsp;XmlJavaTypeAdapter</h4></div></div></div><p><a class="link" href="http://jaxb.java.net/nonav/jaxb20-fcs/docs/api/index.html?javax/xml/bind/annotation//adapters/XmlJavaTypeAdapter.html" target="_top"><code class="literal">XmlJavaTypeAdapter</code></a> allows you to de-couple the
        in-memory representation and the XML representation by introducing an
        intermediate representation. The basic model is as follows:</p><div class="informalexample"><pre class="programlisting">In-memory objects  &lt;===&gt;  Intermediate objects   &lt;===&gt;
XML
                  adapter                         JAXB</pre></div><p>Your adapter code will be responsible for converting in-memory
        objects to/from intermediate objects. Intermediate objects are then
        bound to XML by following the standard JAXB rules. See <a class="link" href="http://jaxb.java.net/nonav/jaxb20-fcs/docs/api/index.html?javax/xml/bind/annotation//adapters/XmlAdapter.html" target="_top"><code class="literal">XmlAdapter</code></a> for a general description of how
        adapters works.</p><p>Adapters extend from the <a class="link" href="http://jaxb.java.net/nonav/jaxb20-fcs/docs/api/index.html?javax/xml/bind/annotation//adapters/XmlAdapter.html" target="_top"><code class="literal">XmlAdapter</code></a> class and provide two methods
        "unmarshal" and "marshal" that converts values in both directions, and
        then the <a class="link" href="http://jaxb.java.net/nonav/jaxb20-fcs/docs/api/index.html?javax/xml/bind/annotation//adapters/XmlJavaTypeAdapter.html" target="_top"><code class="literal">XmlJavaTypeAdapter</code></a> annotation is used to tell
        JAXB where and what adapters kick in.</p><p>(TODO: more info about XmlJavaTypeAdapter needed)</p><div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem"><p>adapting a class</p></li><li class="listitem"><p>adapting a property</p></li><li class="listitem"><p>adapting an external class</p></li><li class="listitem"><p>adapting a collection and its effect</p></li><li class="listitem"><p>adapting and using interfaces</p></li></ol></div></div><div class="section" title="3.4.2.&nbsp;Using XmlJavaTypeAdapter for element/attribute values"><div class="titlepage"><div><div><h4 class="title" id="Using_XmlJavaTypeAdapter_for_element_attribute_values">3.4.2.&nbsp;Using XmlJavaTypeAdapter for element/attribute values</h4></div></div></div><p>One of the common use cases of <a class="link" href="http://jaxb.java.net/nonav/jaxb20-fcs/docs/api/index.html?javax/xml/bind/annotation//adapters/XmlJavaTypeAdapter.html" target="_top"><code class="literal">XmlJavaTypeAdapter</code></a> is to map a "value object" to
        a string in XML. The following example illustrates how to do this, by
        using <code class="literal">java.awt.Color</code> as an example.</p><div class="example"><a name="d0e2850"></a><p class="title"><b>Example&nbsp;54.&nbsp;Mapping Color to #RRGGBB</b></p><div class="example-contents"><pre class="programlisting"><span class="Annotation">@XmlRootElement</span>
<span class="ReservedWord">class</span> Box {
  <span class="Annotation">@XmlJavaTypeAdapter(ColorAdapter.class)</span>
  <span class="Annotation">@XmlElement</span>
  Color fill;
}

<span class="ReservedWord">class</span> ColorAdapter <span class="ReservedWord">extends</span> XmlAdapter&lt;String,Color&gt; {
  <span class="ReservedWord">public</span> Color unmarshal(String s) {
    <span class="ReservedWord">return</span> Color.decode(s);
  }
  <span class="ReservedWord">public</span> String marshal(Color c) {
    <span class="ReservedWord">return</span> <span class="String">"#"</span>+Integer.toHexString(c.getRGB());
  }
}</pre></div></div><br class="example-break"><p>This maps to the following XML representation:</p><div class="example"><a name="d0e2857"></a><p class="title"><b>Example&nbsp;55.&nbsp;Box instance</b></p><div class="example-contents"><pre class="programlisting"><span class="ReservedWord">&lt;box&gt;</span>
  <span class="ReservedWord">&lt;fill&gt;</span>#112233<span class="ReservedWord">&lt;/fill&gt;</span>
<span class="ReservedWord">&lt;/box&gt;</span></pre></div></div><br class="example-break"><p>Since <a class="link" href="http://jaxb.java.net/nonav/jaxb20-fcs/docs/api/index.html?javax/xml/bind/annotation//adapters/XmlJavaTypeAdapter.html" target="_top"><code class="literal">XmlJavaTypeAdapter</code></a> is on a field, this adapter
        only kicks in for this particular field. If you have many
        <code class="literal">Color</code> fields and would like them all to use the same
        adapter, you can move the annotation to a package:</p><div class="example"><a name="d0e2871"></a><p class="title"><b>Example&nbsp;56.&nbsp;package-info.java</b></p><div class="example-contents"><pre class="programlisting"><span class="Annotation">@XmlJavaTypeAdapter(type=Color.class,value=ColorAdapter.class)</span>
<span class="ReservedWord">package</span> foo;</pre></div></div><br class="example-break"><div class="example"><a name="d0e2876"></a><p class="title"><b>Example&nbsp;57.&nbsp;Box.java</b></p><div class="example-contents"><pre class="programlisting"><span class="Annotation">@XmlRootElement</span>
<span class="ReservedWord">class</span> Box {
  <span class="Annotation">@XmlElement</span> Color fill;
  <span class="Annotation">@XmlElement</span> Color border;
}</pre></div></div><br class="example-break"><p>This causes all the fields in the classes in the
        <code class="literal">foo</code> package to use the same specified adapter.</p><p>Also see the <code class="literal">DatatypeConverter</code> class that defines a
        series of basic conversion routines that you may find useful.</p></div><div class="section" title="3.4.3.&nbsp;Pair property"><div class="titlepage"><div><div><h4 class="title" id="Pair_property">3.4.3.&nbsp;Pair property</h4></div></div></div><p>Another useful technique is to define two properties, one for
        JAXB and the other for your application. See the following
        example:</p><div class="example"><a name="d0e2896"></a><p class="title"><b>Example&nbsp;58.&nbsp;Pair property sample</b></p><div class="example-contents"><pre class="programlisting"><span class="Annotation">@XmlRootElement</span>
<span class="ReservedWord">class</span> Person {
  <span class="ReservedWord">private</span> <span class="ReservedWord">int</span> age;

  <span class="Comment">// This public property is for users</span>
  <span class="Annotation">@XmlTransient</span>
  <span class="ReservedWord">public</span> <span class="ReservedWord">int</span> getAge() {
    <span class="ReservedWord">return</span> age;
  }
  <span class="ReservedWord">public</span> <span class="ReservedWord">void</span> setAge(<span class="ReservedWord">int</span> age) {
    <span class="ReservedWord">this</span>.age = age;
  }

  <span class="Comment">// This property is for JAXB</span>
  <span class="Annotation">@XmlAttribute(name="age")</span>
  <span class="ReservedWord">private</span> String getAge_() {
    <span class="ReservedWord">if</span>(age==-<span class="Numeric">1</span>)  <span class="ReservedWord">return</span> <span class="String">"dead"</span>;
    <span class="ReservedWord">else</span>         <span class="ReservedWord">return</span> String.valueOf(age);
  }
  <span class="ReservedWord">private</span> <span class="ReservedWord">void</span> setAge_(String v) <span class="ReservedWord">throws</span> NumberFormatException {
    <span class="ReservedWord">if</span>(v.equals(<span class="String">"dead"</span>))   <span class="ReservedWord">this</span>.age=-<span class="Numeric">1</span>;
    <span class="ReservedWord">else</span>                   <span class="ReservedWord">this</span>.age=Integer.parseInt(age);
}</pre></div></div><br class="example-break"><p>The main "<code class="literal">age</code>" property is public, but marked as <a class="link" href="http://jaxb.java.net/nonav/jaxb20-fcs/docs/api/index.html?javax/xml/bind/annotation//3.4.2XmlTransient.html" target="_top"><code class="literal">XmlTransient</code></a> , so it's exposed in your program,
        but JAXB will not map this to XML. There's another private "<code class="literal">age_</code>"
        property. Since this is marked with <a class="link" href="http://jaxb.java.net/nonav/jaxb20-fcs/docs/api/index.html?javax/xml/bind/annotation//3.4.2XmlAttribute.html" target="_top"><code class="literal">XmlAttribute</code></a> , this is what JAXB is going to use
        to map to the attribute. The getter and setter methods on this
        property will handle the conversion between the in-memory
        representation and the XML representation.</p></div></div><div lang="en" class="section" title="3.5.&nbsp;Mapping cyclic references to XML"><div class="titlepage"><div><div><h3 class="title" id="annotating-your-classes-mapping-cyclic-references-to-xml">3.5.&nbsp;Mapping cyclic references to XML</h3></div></div></div><p>Object models designed in Java often have cycles, which prevent
    straight-forward conversion to XML by JAXB. In fact, when you try to
    marshal an object tree that contains a cycle, the JAXB marshaller reports
    an error, pointing out the objects that formed the cycle. This is because
    JAXB by itself cannot figure out how to cut cycles into a tree.</p><p>Thus it is your responsibility to annotate classes and use other
    means to "tell" JAXB how to handle a cycle. This chapter talks about
    various techniques to do this.</p><div class="section" title="3.5.1.&nbsp;Parent pointers"><div class="titlepage"><div><div><h4 class="title" id="Parent_pointers">3.5.1.&nbsp;Parent pointers</h4></div></div></div><p>One of the very common forms of cycle is a parent pointer. The
        following example illustrates a typical parent pointer, and how this
        can be turned into "natural" XML:</p><div class="example"><a name="d0e2930"></a><p class="title"><b>Example&nbsp;59.&nbsp;Classes with parent pointer</b></p><div class="example-contents"><pre class="programlisting"><span class="Annotation">@XmlRootElement</span>
<span class="ReservedWord">class</span> Department {
  <span class="Annotation">@XmlAttribute</span>
  String name;
  <span class="Annotation">@XmlElement(name="employee")</span>
  List&lt;Employee&gt; employees;
}

<span class="ReservedWord">class</span> Employee {
  <span class="Annotation">@XmlTransient</span>
  Department department;  <span class="Comment">// parent pointer</span>
  <span class="Annotation">@XmlAttribute</span>
  String name;

  <span class="ReservedWord">public</span> <span class="ReservedWord">void</span> afterUnmarshal(Unmarshaller u, Object parent) {
    <span class="ReservedWord">this</span>.department = (Department)parent;
  }
}</pre></div></div><br class="example-break"><p>This will produce the following XML:</p><div class="example"><a name="d0e2937"></a><p class="title"><b>Example&nbsp;60.&nbsp;XML view of department</b></p><div class="example-contents"><pre class="programlisting"><span class="ReservedWord">&lt;department</span> <span class="Identifier">name</span>=<span class="String">"accounting"</span><span class="ReservedWord">&gt;</span>
  <span class="ReservedWord">&lt;employee</span> <span class="Identifier">name</span>=<span class="String">"Joe Chin"</span><span class="ReservedWord"> /&gt;</span>
  <span class="ReservedWord">&lt;employee</span> <span class="Identifier">name</span>=<span class="String">"Adam Smith"</span><span class="ReservedWord"> /&gt;</span>
  ...
<span class="ReservedWord">&lt;/department&gt;</span></pre></div></div><br class="example-break"><p>And reading this document back into Java objects will produce
        the expected tree with all the proper parent pointers set up
        correctly.</p><p>The first technique here is the use of <a class="link" href="http://jaxb.java.net/nonav/jaxb20-fcs/docs/api/index.html?javax/xml/bind/annotation//3.5.1XmlTransient.html" target="_top"><code class="literal">XmlTransient</code></a> on the parent pointer. This tells
        JAXB that you don't need this parent pointer to be represented
        explicitly in XML, because the fact that <code class="literal">employee</code> is
        always contained inside <code class="literal">department</code> implies the
        parent/child relationship. This causes the marshaller to produce the
        expected XML. However, when you unmarshal it, since this field is not
        bound, the <code class="literal">Employee.department</code> field will be left
        null.</p><p>That's where the second technique comes in, which is the use of
        the <code class="literal">afterUnmarshal</code> callback. This method is invoked by
        the JAXB implementation on each instance when the unmarshalling of a
        <code class="literal">Employee</code> object completes. Furthermore, the second
        parameter to the method is the parent object, which in this case is a
        <code class="literal">Department</code> object. So in this example, this sets up the
        parent pointer correctly.</p><p>This callback can be also used to perform other
        post-unmarshalling set up work.</p></div><div class="section" title="3.5.2.&nbsp;Many-to-many relationship"><div class="titlepage"><div><div><h4 class="title" id="Many_to_many_relationship">3.5.2.&nbsp;Many-to-many relationship</h4></div></div></div><p>TBD</p></div><div class="section" title="3.5.3.&nbsp;@XmlID and @XmlIDREF"><div class="titlepage"><div><div><h4 class="title" id="_XmlID_and__XmlIDREF">3.5.3.&nbsp;<code class="literal">@XmlID</code> and
        <code class="literal">@XmlIDREF</code></h4></div></div></div><p>When a reference to another object is annotated with <a class="link" href="http://jaxb.java.net/nonav/jaxb20-fcs/docs/api/index.html?javax/xml/bind/annotation//3.5.3XmlIDREF.html" target="_top"><code class="literal">XmlIDREF</code></a> , its corresponding XML it will be
        referenced by <code class="literal">xs:IDREF</code>, instead of containment. See below
        for an example:</p><p>Example of <code class="literal">@XmlID</code> and
        <code class="literal">@XmlIDREF</code></p><div class="informalexample"><pre class="programlisting"><span class="Annotation">@XmlRootElement</span>
<span class="ReservedWord">class</span> Root {
  List&lt;Foo&gt; foos;
  List&lt;Bar&gt; bars;
}
<span class="ReservedWord">class</span> Foo {
  <span class="Comment">// you don't have to make it an attribute, but that's more common</span>
  <span class="Annotation">@XmlAttribute</span> <span class="Annotation">@XmlIDREF</span> Bar bar;
}
<span class="ReservedWord">class</span> Bar {
  <span class="Comment">// you don't have to make it an attribute, but that's more common</span>
  <span class="Annotation">@XmlAttribute</span> <span class="Annotation">@XmlID</span> String id;
}</pre></div><div class="example"><a name="d0e3003"></a><p class="title"><b>Example&nbsp;61.&nbsp;Schema for above</b></p><div class="example-contents"><pre class="programlisting"><span class="ReservedWord">&lt;xs:complexType</span> <span class="Identifier">name</span>=<span class="String">"foo"</span><span class="ReservedWord">&gt;</span>
  <span class="ReservedWord">&lt;xs:sequence/&gt;</span>
  <span class="ReservedWord">&lt;xs:attribute</span> <span class="Identifier">name</span>=<span class="String">"bar"</span> <span class="Identifier">type</span>=<span class="String">"xs:IDREF"</span><span class="ReservedWord">/&gt;</span>
  <span class="ReservedWord">&lt;/xs:sequence&gt;</span>
<span class="ReservedWord">&lt;/xs:complexType&gt;</span>
<span class="ReservedWord">&lt;xs:complexType</span> <span class="Identifier">name</span>=<span class="String">"bar"</span><span class="ReservedWord">&gt;</span>
  <span class="ReservedWord">&lt;xs:sequence/&gt;</span>
  <span class="ReservedWord">&lt;xs:attribute</span> <span class="Identifier">name</span>=<span class="String">"id"</span> <span class="Identifier">type</span>=<span class="String">"xs:ID"</span><span class="ReservedWord">/&gt;</span>
<span class="ReservedWord">&lt;/xs:complexType&gt;</span></pre></div></div><br class="example-break"><div class="example"><a name="d0e3008"></a><p class="title"><b>Example&nbsp;62.&nbsp;A sample instance</b></p><div class="example-contents"><pre class="programlisting"><span class="ReservedWord">&lt;root&gt;</span>
  <span class="ReservedWord">&lt;foo</span> <span class="Identifier">bar</span>=<span class="String">"x"</span><span class="ReservedWord">/&gt;</span>
  <span class="ReservedWord">&lt;foo</span> <span class="Identifier">bar</span>=<span class="String">"y"</span><span class="ReservedWord">/&gt;</span>
  <span class="ReservedWord">&lt;bar</span> <span class="Identifier">id</span>=<span class="String">"x"</span><span class="ReservedWord">/&gt;</span>
  <span class="ReservedWord">&lt;bar</span> <span class="Identifier">id</span>=<span class="String">"y"</span><span class="ReservedWord">/&gt;</span>
<span class="ReservedWord">&lt;/root&gt;</span></pre></div></div><br class="example-break"><p>There are a few things to consider when you do this. First, the
        object to be referenced must have an ID that is unique within the
        whole document. You'd also need to ensure that the referenced objects
        are <span class="emphasis"><em>contained</em></span> somewhere else (like in the
        <code class="literal">Root</code> class in this case), or else <code class="literal">Bar</code>
        objects will never be marshalled. This technique can be used to remove
        the cyclic references, but it's only possible when your object model
        has an easy cut point.</p></div><div class="section" title="3.5.4.&nbsp;Use the CycleRecoverable interface"><div class="titlepage"><div><div><h4 class="title" id="Use_the_CycleRecoverable_interface">3.5.4.&nbsp;Use the CycleRecoverable interface</h4></div></div></div><p>Starting 2.1 EA2, the JAXB RI exposes <a class="link" href="http://fisheye5.cenqua.com/browse/jaxb2-sources/jaxb-ri/runtime/src/com/sun/xml/bind/CycleRecoverable.java?r=jaxb-2_1-branch" target="_top"><code class="literal">CycleRecoverable</code></a> interface. Applications can
        choose to implement this interface in some of its objects. When a
        cyclic reference is detected during marshalling, and if the object
        that formed a cycle implements this interface, then the method on this
        interface is called to allow an application to nominate its
        replacement to be written to XML. In this way, the application can
        recover from a cycle gracefully.</p><p>See <a class="link" href="http://forums.java.net/jive/thread.jspa?threadID=13670&amp;start=15#158545" target="_top">a
        posting from <code class="literal">gadams00</code></a> for a complete illustration
        of this feature.</p><p>This technique allows you to cope with a situation where you
        cannot easily determine upfront as to where a cycle might happen. On
        the other hand, this feature is a JAXB RI feature. Another downside of
        this is that unless you nominate your replacement carefully, you can
        make the marshalling output invalid with respect to the schema, and
        thus you might hit another problem when you try to read it back
        later.</p></div></div></div><div lang="en" class="section" title="4.&nbsp;Unmarshalling"><div class="titlepage"><div><div><h2 class="title" style="clear: both" id="unmarshalling">4.&nbsp;Unmarshalling</h2></div></div></div><div lang="en" class="section" title="4.1.&nbsp;@XmlRootElement and unmarshalling"><div class="titlepage"><div><div><h3 class="title" id="unmarshalling-xmlrootelement-and-unmarshalling">4.1.&nbsp;<code class="literal">@XmlRootElement</code> and unmarshalling</h3></div></div></div><p>Classes with <a class="link" href="http://jaxb.java.net/nonav/jaxb20-fcs/docs/api/index.html?javax/xml/bind/annotation//4.1XmlRootElement.html" target="_top"><code class="literal">XmlRootElement</code></a> can be unmarshalled from XML elements
    simply by invoking the unmarshal method that takes one parameter. This is
    the simplest mode of unmarshalling.</p><p>Unmarshalling with <code class="literal">@XmlRootElement</code></p><div class="informalexample"><pre class="programlisting"><span class="Annotation">@XmlRootElement</span>
<span class="ReservedWord">class</span> Foo {
  <span class="Annotation">@XmlAttribute</span>
  String name;
  <span class="Annotation">@XmlElement</span>
  String content;
}

Unmarshaller u = ...;
Foo foo = (Foo)u.unmarshal(<span class="ReservedWord">new</span> File(<span class="String">"foo.xml"</span>));</pre></div><div class="example"><a name="d0e3065"></a><p class="title"><b>Example&nbsp;63.&nbsp;foo.xml</b></p><div class="example-contents"><pre class="programlisting"><span class="ReservedWord">&lt;foo</span> <span class="Identifier">name</span>=<span class="String">"something"</span><span class="ReservedWord">&gt;</span>
  <span class="ReservedWord">&lt;content&gt;</span>abc<span class="ReservedWord">&lt;/content&gt;</span>
<span class="ReservedWord">&lt;/foo&gt;</span></pre></div></div><br class="example-break"><p>However, sometimes you may need to unmarshal an instance of a type
    that does not have an <a class="link" href="http://jaxb.java.net/nonav/jaxb20-fcs/docs/api/index.html?javax/xml/bind/annotation//4.1XmlRootElement.html" target="_top"><code class="literal">XmlRootElement</code></a> . For example, you might dynamically
    find out at the runtime that a certain element has a certain type. For
    example, the following document illustrates an XML instance where the
    content of <code class="literal">&lt;someOtherTagName&gt;</code> element is represented by the
    <code class="literal">Foo</code> class.</p><div class="example"><a name="d0e3082"></a><p class="title"><b>Example&nbsp;64.&nbsp;foo2.xml</b></p><div class="example-contents"><pre class="programlisting"><span class="ReservedWord">&lt;someOtherTagName</span> <span class="Identifier">name</span>=<span class="String">"something"</span><span class="ReservedWord">&gt;</span>
  <span class="ReservedWord">&lt;content&gt;</span>abc<span class="ReservedWord">&lt;/content&gt;</span>
<span class="ReservedWord">&lt;/someOtherTagName&gt;</span></pre></div></div><br class="example-break"><p>To unmarshal this into a <code class="literal">Foo</code> class, use the version of
    the <code class="literal">unmarshal</code> method that takes the 'expectedType' argument,
    as follows:</p><div class="example"><a name="d0e3095"></a><p class="title"><b>Example&nbsp;65.&nbsp;Unmarshalling into a known type</b></p><div class="example-contents"><pre class="programlisting">Unmarshaller u = ...;
JAXBElement&lt;Foo&gt; root = u.unmarshal(<span class="ReservedWord">new</span> StreamSource(<span class="ReservedWord">new</span> File(<span class="String">"foo.xml"</span>)),Foo.<span class="ReservedWord">class</span>);
Foo foo = root.getValue();</pre></div></div><br class="example-break"><p>To reduce the number of the <code class="literal">unmarshal</code> methods, this
    two-argument version is not defined for every single-argument version. So
    as in this example, you might need to perform additional wrapping of the
    input parameter.</p><p>This instructs JAXB that the caller is expecting to unmarshal
    <code class="literal">Foo</code> instance. JAXB returns a <code class="literal">JAXBElement</code> of
    <code class="literal">Foo</code>, and this <code class="literal">JAXBElement</code> captures the tag name
    of the root element.</p></div><div lang="en" class="section" title="4.2.&nbsp;Unmarshalling is not working! Help!"><div class="titlepage"><div><div><h3 class="title" id="unmarshalling-unmarshalling-is-not-working-help">4.2.&nbsp;Unmarshalling is not working! Help!</h3></div></div></div><p>There are a few common causes for this problem. These causes often
    exhibit similar symptoms:</p><div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem"><p>Instance documents are invalid</p></li><li class="listitem"><p><code class="literal">JAXBContext</code> is not created correctly.</p></li></ol></div><div class="section" title="4.2.1.&nbsp;Make sure your instance document is valid"><div class="titlepage"><div><div><h4 class="title" id="Make_sure_your_instance_document_is_valid">4.2.1.&nbsp;Make sure your instance document is valid</h4></div></div></div><p>First, use an independent schema validator to check if your
        document is really valid with respect to the schema you compiled. When
        the root element of a document is invalid, then the unmarshaller will
        issue "unexpected element" errors. When a portion of a document is
        invalid, JAXB skips that portion, so the end result is that the
        unmarshalling returns normally, yet you notice that a part of the
        content tree is missing. This is often the desirable behavior, but it
        sometimes ends up masking a problem.</p><p>Also, try to install <code class="literal">ValidationEventHandler</code> on the
        unmarshaller. When a portion of a document is skipped, the
        unmarshaller notifies a <code class="literal">ValidationEventHandler</code>, so it
        allows you to see what's going on.</p><div class="example"><a name="d0e3147"></a><p class="title"><b>Example&nbsp;66.&nbsp;Installing ValidationEventHandler</b></p><div class="example-contents"><pre class="programlisting">Unmarshaller u = ...;
<span class="Comment">// this implementation is a part of the API and convenient for trouble-shooting,</span>
<span class="Comment">// as it prints out errors to System.out</span>
u.setEventHandler(<span class="ReservedWord">new</span> javax.xml.bind.helpers.DefaultValidationEventHandler());

u.unmarshal(<span class="ReservedWord">new</span> File(<span class="String">"foo.xml"</span>));</pre></div></div><br class="example-break"><p>Also consider installing a <code class="literal">Schema</code> object to the
        unmarshaller, so that the unmarshaller performs a schema validation
        while unmarshalling. Earlier I suggested that you try an independent
        schema validator, but for various reasons (not all tools are reliable,
        you might have made an error and used a different schema/instance),
        using validating unmarshalling is a better way to guarantee the
        validity of your instance document being unmarshalled. Please follow
        the <a class="link" href="http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JAXPIntro.html#wp65584" target="_top">JAXP
        tutorial</a> for more about how to construct a <code class="literal">Schema</code>
        object from your schema.</p><p>If you are unmarshalling from XML parser APIs (such as DOM, SAX,
        StAX), then also make sure that the parser/DOM is configured with the
        namespace enabled.</p></div><div class="section" title="4.2.2.&nbsp;Check if your JAXBContext is correct"><div class="titlepage"><div><div><h4 class="title" id="Check_if_your_JAXBContext_is_correct">4.2.2.&nbsp;Check if your JAXBContext is correct</h4></div></div></div><p>(TODO: This also applies to the marshaller. Think about moving
        it.)</p><p>The other possibility is that <code class="literal">JAXBContext</code> is not
        set up correctly. <code class="literal">JAXBContext</code> "knows" a set of classes,
        and if it doesn't know a class that it's supposed to know, then the
        unmarshaller may fail to perform as you expected.</p><p>To verify that you created <code class="literal">JAXBContext</code> correctly,
        call <code class="literal">JAXBContext.toString()</code>. It will output the list of
        classes it knows. If a class is not in this list, the unmarshaller
        will never return an instance of that class. Make you see all the
        classes you expect to be returned from the unmarshaller in the list.
        When dealing with a large schema that spans across a large number of
        classes and packages, this is one possible cause of a problem.</p><p>If you noticed that a class is missing, explicitly specify that
        to <code class="literal">JAXBContext.newInstance</code>. If you are binding classes
        that are generated from XJC, then the easiest way to include all the
        classes is to specify the generated <code class="literal">ObjectFactory</code>
        class(es).</p></div></div><div lang="en" class="section" title="4.3.&nbsp;Element default values and unmarshalling"><div class="titlepage"><div><div><h3 class="title" id="unmarshalling-element-default-values-and-unmarshalling">4.3.&nbsp;Element default values and unmarshalling</h3></div></div></div><p>Because of the "strange" way that element default values in XML
    Schema work, people often get confused about their behavior. This section
    describes how this works.</p><p>When a class has an element property with the default value, and if
    the document you are reading is missing the element, then the unmarshaller
    does <span class="emphasis"><em>not</em></span> fill the field with the default value.
    Instead, the unmarshaller fills in the field when the element is present
    but the content is missing. See below:</p><div class="example"><a name="d0e3205"></a><p class="title"><b>Example&nbsp;67.&nbsp;XML instance 1</b></p><div class="example-contents"><pre class="programlisting"><span class="ReservedWord">&lt;foo /&gt;</span></pre></div></div><br class="example-break"><div class="example"><a name="d0e3210"></a><p class="title"><b>Example&nbsp;68.&nbsp;XML instance 2</b></p><div class="example-contents"><pre class="programlisting"><span class="ReservedWord">&lt;foo&gt;</span>
  <span class="ReservedWord">&lt;a/&gt;</span>  <span class="Comment">&lt;!-- or &lt;a&gt;&lt;/a&gt; --&gt;</span>
<span class="ReservedWord">&lt;/foo&gt;</span></pre></div></div><br class="example-break"><div class="example"><a name="d0e3215"></a><p class="title"><b>Example&nbsp;69.&nbsp;XML instance 3</b></p><div class="example-contents"><pre class="programlisting"><span class="ReservedWord">&lt;foo&gt;</span>
  <span class="ReservedWord">&lt;a&gt;</span>abc<span class="ReservedWord">&lt;/a&gt;</span>
<span class="ReservedWord">&lt;/foo&gt;</span></pre></div></div><br class="example-break"><div class="example"><a name="d0e3220"></a><p class="title"><b>Example&nbsp;70.&nbsp;Element defaults and XML</b></p><div class="example-contents"><pre class="programlisting"><span class="Annotation">@XmlRootElement</span>
<span class="ReservedWord">class</span> Foo {
  <span class="Annotation">@XmlElement(defaultValue="value")</span> <span class="ReservedWord">public</span> String a=null;
}

Foo foo = unmarshaller.unmarshal(<span class="String">"instance1.xml"</span>);
System.out.println(foo.a);   <span class="Comment">// null</span>

Foo foo = unmarshaller.unmarshal(<span class="String">"instance2.xml"</span>);
System.out.println(foo.a);   <span class="Comment">// "value". The default kicked in.</span>

Foo foo = unmarshaller.unmarshal(<span class="String">"instance3.xml"</span>);
System.out.println(foo.a);   <span class="Comment">// "abc". Read from the instance.</span></pre></div></div><br class="example-break"><p>This is consistent with the XML Schema spec, where it essentially
    states that the element defaults do not kick in when the element is
    absent, so unfortunately we can't change this behavior.</p><p>Depending on your expectation, using a field initializer may achieve
    what you are looking for. See below:</p><div class="example"><a name="d0e3229"></a><p class="title"><b>Example&nbsp;71.&nbsp;Possible changes by using field initializer</b></p><div class="example-contents"><pre class="programlisting"><span class="Annotation">@XmlRootElement</span>
<span class="ReservedWord">class</span> Foo {
  <span class="Annotation">@XmlElement</span> <span class="ReservedWord">public</span> String a=<span class="String">"value"</span>;
}

Foo foo = unmarshaller.unmarshal(<span class="String">"instance1.xml"</span>);
System.out.println(foo.a);   <span class="Comment">// "value", because JAXB didn't overwrite the value</span>

Foo foo = unmarshaller.unmarshal(<span class="String">"instance2.xml"</span>);
System.out.println(foo.a);   <span class="Comment">// "", because &lt;a&gt; element had 0-length string in it</span>

Foo foo = unmarshaller.unmarshal(<span class="String">"instance3.xml"</span>);
System.out.println(foo.a);   <span class="Comment">// "abc". Read from the instance.</span></pre></div></div><br class="example-break"><p>Alternatively, attribute default values work in a way that agrees
    with the typical expectation, so consider using that. Also, see <a class="xref" href="ch03.html#marshalling-element-default-values-and-marshalling" title="5.2.&nbsp;Element default values and marshalling">Element default values and marshalling</a>.</p></div><div lang="en" class="section" title="4.4.&nbsp;Dealing with large documents"><div class="titlepage"><div><div><h3 class="title" id="unmarshalling-dealing-with-large-documents">4.4.&nbsp;Dealing with large documents</h3></div></div></div><p>JAXB API is designed to make it easy to read the whole XML document
    into a single tree of JAXB objects. This is the typical use case, but in
    some situations this is not desirable. Perhaps:</p><div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem"><p>A document is huge and therefore the whole may not fit the
            memory.</p></li><li class="listitem"><p>A document is a live stream of XML (such as <a class="link" href="http://www.xmpp.org/" target="_top">XMPP</a>) and therefore you
            can't wait for the EOF.</p></li><li class="listitem"><p>You only need to databind the portion of a document and
            would like to process the rest in other XML APIs.</p></li></ol></div><p>This section discusses several advanced techniques to deal with
    these situations.</p><div class="section" title="4.4.1.&nbsp;Processing a document by chunk"><div class="titlepage"><div><div><h4 class="title" id="Processing_a_document_by_chunk">4.4.1.&nbsp;Processing a document by chunk</h4></div></div></div><p>When a document is large, it's usually because there's
        repetitive parts in it. Perhaps it's a purchase order with a large
        list of line items, or perhaps it's an XML log file with large number
        of log entries.</p><p>This kind of XML is suitable for chunk-processing; the main idea
        is to use the StAX API, run a loop, and unmarshal individual chunks
        separately. Your program acts on a single chunk, and then throws it
        away. In this way, you'll be only keeping at most one chunk in memory,
        which allows you to process large documents.</p><p>See the streaming-unmarshalling example and the
        partial-unmarshalling example in the JAXB RI distribution for more
        about how to do this. The streaming-unmarshalling example has an
        advantage that it can handle chunks at arbitrary nest level, yet it
        requires you to deal with the push model --- JAXB unmarshaller will
        "<code class="literal">push</code>" new chunk to you and you'll need to process them right
        there.</p><p>In contrast, the partial-unmarshalling example works in a pull
        model (which usually makes the processing easier), but this approach
        has some limitations in databinding portions other than the repeated
        part.</p></div><div class="section" title="4.4.2.&nbsp;Processing a live stream of XML"><div class="titlepage"><div><div><h4 class="title" id="Processing_a_live_stream_of_XML">4.4.2.&nbsp;Processing a live stream of XML</h4></div></div></div><p>The techniques discussed above can be used to handle this case
        as well, since they let you unmarshal chunks one by one. See the
        xml-channel example in the JAXB RI distribution for more about how to
        do this.</p></div><div class="section" title="4.4.3.&nbsp;Creating virtual infosets"><div class="titlepage"><div><div><h4 class="title" id="Creating_virtual_infosets">4.4.3.&nbsp;Creating virtual infosets</h4></div></div></div><p>For further advanced cases, one could always run a streaming
        infoset conversion outside JAXB API and basically curve just the
        portion of the infoset you want to data-bind, and feed it as a
        complete infoset into JAXB API. JAXB API accepts XML infoset in many
        different forms (DOM, SAX, StAX), so there's a fair amount of
        flexibility in choosing the right trade off between the development
        effort in doing this and the runtime performance.</p><p>For more about this, refer to the respective XML infoset
        API.</p></div></div></div><div lang="en" class="section" title="5.&nbsp;Marshalling"><div class="titlepage"><div><div><h2 class="title" style="clear: both" id="marshalling">5.&nbsp;Marshalling</h2></div></div></div><div lang="en" class="section" title="5.1.&nbsp;Changing prefixes"><div class="titlepage"><div><div><h3 class="title" id="marshalling-changing-prefixes">5.1.&nbsp;Changing prefixes</h3></div></div></div><p>By default, a JAXB marshaller uses random namespace prefixes (such
    as <code class="literal">ns1</code>, <code class="literal">ns2</code>, ...) when it needs to declare new
    namespace URIs. While this is perfectly valid XML wrt the schema, for
    human readability, you might want to change them to something that makes
    more sense.</p><p>The JAXB RI defines NamespacePrefixMapper to allow you to do this. See
    the <code class="literal">namespace-prefix</code> sample in the distribution for more
    details.</p></div><div lang="en" class="section" title="5.2.&nbsp;Element default values and marshalling"><div class="titlepage"><div><div><h3 class="title" id="marshalling-element-default-values-and-marshalling">5.2.&nbsp;Element default values and marshalling</h3></div></div></div><p>Because of a "strange" way element default values in XML Schema
    work, people often get confused about its behavior. This section describes
    how this works.</p><p>When a class has an element property with the default value, and if
    a value is null, then the marshaller will not produce the corresponding
    element in XML:</p><div class="example"><a name="d0e3314"></a><p class="title"><b>Example&nbsp;72.&nbsp;Element defaults and XML</b></p><div class="example-contents"><pre class="programlisting"><span class="Annotation">@XmlRootElement</span>
<span class="ReservedWord">class</span> Foo {
  <span class="Annotation">@XmlElement(defaultValue="value")</span> <span class="ReservedWord">public</span> String a=null;
}

marshaller.marshal(<span class="ReservedWord">new</span> Foo(),System.out);</pre></div></div><br class="example-break"><div class="example"><a name="d0e3319"></a><p class="title"><b>Example&nbsp;73.&nbsp;Marshalling output from above</b></p><div class="example-contents"><pre class="programlisting"><span class="ReservedWord">&lt;foo /&gt;</span></pre></div></div><br class="example-break"><p>This is consistent with the XML Schema spec, where it essentially
    states that the element defaults do not kick in when the element is
    absent. Attribute default values do not have this problem, so if you can
    change the schema, changing it to an attribute is usually a better idea.
    Alternatively, depending on your expectation, setting the field to a
    default value in Java may achieve what you are looking for.</p><div class="example"><a name="d0e3326"></a><p class="title"><b>Example&nbsp;74.&nbsp;Possible changes</b></p><div class="example-contents"><pre class="programlisting"><span class="Annotation">@XmlRootElement</span>
<span class="ReservedWord">class</span> Foo {
  <span class="Annotation">@XmlElement</span> <span class="ReservedWord">public</span> String a=<span class="String">"value"</span>;
}
<span class="Annotation">@XmlRootElement</span>
<span class="ReservedWord">class</span> Bar {
  <span class="Annotation">@XmlAttribute</span> <span class="ReservedWord">public</span> String a;
}

marshaller.marshal(<span class="ReservedWord">new</span> Foo(),System.out);
marshaller.marshal(<span class="ReservedWord">new</span> Bar(),System.out);</pre></div></div><br class="example-break"><div class="example"><a name="d0e3331"></a><p class="title"><b>Example&nbsp;75.&nbsp;Marshalling output from above</b></p><div class="example-contents"><pre class="programlisting"><span class="ReservedWord">&lt;foo&gt;</span>
    <span class="ReservedWord">&lt;a&gt;</span>value<span class="ReservedWord">&lt;/a&gt;</span>
<span class="ReservedWord">&lt;/foo&gt;</span>

<span class="ReservedWord">&lt;bar/&gt;</span></pre></div></div><br class="example-break"><p>Also, see <a class="xref" href="ch03.html#unmarshalling-element-default-values-and-unmarshalling" title="4.3.&nbsp;Element default values and unmarshalling">Element default values and unmarshalling</a>.</p></div><div lang="en" class="section" title="5.3.&nbsp;Different ways of marshalling"><div class="titlepage"><div><div><h3 class="title" id="marshalling-different-ways-of-marshalling">5.3.&nbsp;Different ways of marshalling</h3></div></div></div><div class="section" title="5.3.1.&nbsp;Different output media"><div class="titlepage"><div><div><h4 class="title" id="Different_output_media">5.3.1.&nbsp;Different output media</h4></div></div></div><p>The most basic notion of the marshalling is to take a JAXB-bound
        object that has <code class="literal">@XmlRootElement</code>, and write it out as a
        whole XML document. So perhaps you have a class like this:</p><div class="example"><a name="d0e3352"></a><p class="title"><b>Example&nbsp;76.&nbsp;JAXB POJO</b></p><div class="example-contents"><pre class="programlisting"><span class="ReservedWord">class</span> Point {
  <span class="Annotation">@XmlElement</span>
  <span class="ReservedWord">public</span> <span class="ReservedWord">int</span> x;
  <span class="Annotation">@XmlElement</span>
  <span class="ReservedWord">public</span> <span class="ReservedWord">int</span> y;
  Point(...) { ... }
}</pre></div></div><br class="example-break"><p>Then you can do:</p><div class="example"><a name="d0e3359"></a><p class="title"><b>Example&nbsp;77.&nbsp;Plain marshalling</b></p><div class="example-contents"><pre class="programlisting">marshaller.marshal( <span class="ReservedWord">new</span> Point(<span class="Numeric">1</span>,<span class="Numeric">3</span>), System.out );
marshaller.marshal( <span class="ReservedWord">new</span> Point(<span class="Numeric">1</span>,<span class="Numeric">3</span>), <span class="ReservedWord">new</span> File(<span class="String">"out.xml"</span>) );</pre></div></div><br class="example-break"><p>.. and so on. There're seven <code class="literal">Marshaller.marshal</code>
        methods that takes different output media as the second parameter. If
        you are writing to a file, a socket, or memory, then you should use
        the version that takes <code class="literal">OutputStream</code>. Unless you change
        the target encoding to something else (default is UTF-8), there's a
        special marshaller codepath for <code class="literal">OutputStream</code>, which makes
        it run really fast. You also don't have to use
        <code class="literal">BufferedOutputStream</code>, since the JAXB RI does the adequate
        buffering.</p><p>You can also write to <code class="literal">Writer</code>, but in this case
        you'll be responsible for encoding characters, so in general you need
        to be careful. If you want to marshal XML into an encoding other than
        UTF-8, it's best to use the <code class="literal">JAXB_ENCODING</code> property and
        then write to <code class="literal">OutputStream</code>, as it escapes characters to
        things like <code class="literal">&amp;#x1824;</code> correctly.</p><p>The next medium we support is W3C DOM. This is bit unintuitive,
        but you'll do it like this:</p><div class="example"><a name="d0e3394"></a><p class="title"><b>Example&nbsp;78.&nbsp;Marshal to DOM</b></p><div class="example-contents"><pre class="programlisting">DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
Document doc = dbf.newDocumentBuilder().newDocument();

marshaller.marshal( <span class="ReservedWord">new</span> Point(<span class="Numeric">1</span>,<span class="Numeric">3</span>), doc );</pre></div></div><br class="example-break"><p>And after the method invocation you get a complete DOM tree that
        represents the marshalled document.</p><p>The other versions of the marshal methods are there to write XML
        documents in terms of other XML APIs, such as SAX and StAX. The
        version that takes <code class="literal">ContentHandler</code> is useful when you need
        a custom formatting needs (like you want each attribute to be in new
        line, etc), but otherwise they are not very interesting if you are
        writing a whole document.</p></div><div class="section" title="5.3.2.&nbsp;Marshalling into a subtree"><div class="titlepage"><div><div><h4 class="title" id="Marshalling_into_a_subtree">5.3.2.&nbsp;Marshalling into a subtree</h4></div></div></div><p>Another common use of JAXB is where you are writing a bigger
        document, and you use JAXB to generate part(s) of it. The JAX-WS RI is
        the prime example. It produces a SOAP message, and JAXB is only used
        to produce the body. When you are doing this, you first set
        <code class="literal">JAXB_FRAGMENT</code> property on the marshaller. This changes
        the behaviors of the marshaller so that it works better in this
        situation.</p><p>If you are writing to an <code class="literal">OutputStream</code> or
        <code class="literal">Writer</code> and generally sending it to someone else, you can
        do something like this:</p><div class="example"><a name="d0e3422"></a><p class="title"><b>Example&nbsp;79.&nbsp;Marshalling into a subtree</b></p><div class="example-contents"><pre class="programlisting">System.out.println(<span class="String">"&lt;envelope&gt;"</span>);
marshaller.marshal( object, System.out );
System.out.println(<span class="String">"&lt;/envelope&gt;"</span>);</pre></div></div><br class="example-break"><p>Like I mentioned, this is probably the fastest, even though
        <code class="literal">println</code> isn't very pretty. <code class="literal">JAXB_FRAGMENT</code>
        prevents the marshaller from producing an XML declaration, so the
        above works just fine. The downside of this approach is that if the
        ancestor elements declare the namespaces, JAXB won't be able to take
        advantage of them.</p><p>You can also marshal an object as a subtree of an existing DOM
        tree. To do this, you pass the <code class="literal">Element</code> object as the
        second parameter, and the marshaller will marshal an object as a child
        of this node.</p><p>StAX is also very convenient for doing this sort of things. You
        can create <code class="literal">XMLStreamWriter</code>, write some stuff, and then
        pass that to the marshaller. <code class="literal">JAXB_FRAGMENT</code> prevents the
        marshaller from producing <code class="literal">startDocument</code> and
        <code class="literal">endDocument</code> token. When doing this sub-tree marshaling to
        DOM and StAX, JAXB can take advantage of available in-scope namespace
        bindings.</p><p>Finally, you can marshal an object as a subtree into
        <code class="literal">ContentHandler</code>, but it requires a fair amount of SAX
        programming experience, and it goes beyond the scope of this
        entry.</p></div><div class="section" title="5.3.3.&nbsp;Marshalling a non-element"><div class="titlepage"><div><div><h4 class="title" id="Marshalling_a_non_element">5.3.3.&nbsp;Marshalling a non-element</h4></div></div></div><p>Another common use case is where you have an object that doesn't
        have <code class="literal">@XmlRootElement</code> on it. JAXB allows you to marshal it
        like this:</p><div class="example"><a name="d0e3467"></a><p class="title"><b>Example&nbsp;80.&nbsp;Marshalling a non-element</b></p><div class="example-contents"><pre class="programlisting">marshaller.marshal( <span class="ReservedWord">new</span> JAXBElement(
  <span class="ReservedWord">new</span> QName(<span class="String">""</span>,<span class="String">"rootTag"</span>),Point.<span class="ReservedWord">class</span>,<span class="ReservedWord">new</span> Point(...)));</pre></div></div><br class="example-break"><p>This puts the <code class="literal">&lt;rootTag&gt;</code> element as the root element,
        followed by the contents of the object, then <code class="literal">&lt;/rootTag&gt;</code>. You can
        actually use it with a class that has <code class="literal">@XmlRootElement</code>,
        and that simply renames the root element name.</p><p>At the first glance the second <code class="literal">Point.class</code>
        parameter may look redundant, but it's actually necessary to determine
        if the marshaller will produce (infamous)
        <code class="literal">@xsi</code>:type. In this example, both the class and the
        instance are <code class="literal">Point</code>, so you won't see
        <code class="literal">@xsi</code>:type. But if they are different, you'll see
        it.</p><p>This can be also used to marshal a simple object, like
        <code class="literal">String</code> or an integer.</p><p>Marshalling a non-element with
        <code class="literal">@xsi</code>:type</p><div class="informalexample"><pre class="programlisting">marshaller.marshal( <span class="ReservedWord">new</span> JAXBElement(
  <span class="ReservedWord">new</span> QName(<span class="String">""</span>,<span class="String">"rootTag"</span>),String.<span class="ReservedWord">class</span>,<span class="String">"foo bar"</span>));</pre></div><p>But unfortunately it <span class="bold"><strong>cannot</strong></span> be
        used to marshal objects like <code class="literal">List</code> or <code class="literal">Map</code>, as
        they aren't handled as the first-class citizen in the JAXB
        world.</p></div><div class="section" title="5.3.4.&nbsp;Connecting to other XML APIs"><div class="titlepage"><div><div><h4 class="title" id="Connecting_to_other_XML_APIs">5.3.4.&nbsp;Connecting to other XML APIs</h4></div></div></div><p>Because of the <code class="literal">Source</code> and <code class="literal">Result</code>
        support, JAXB objects can be easily marshalled into other XML APIs
        that are not mentioned here. For example, <a class="link" href="http://www.dom4j.org/" target="_top">dom4j</a> has
        <code class="literal">DocumentResult</code> that extends <code class="literal">Result</code>, so you
        can do:</p><div class="example"><a name="d0e3541"></a><p class="title"><b>Example&nbsp;81.&nbsp;Marshalling to dom4j</b></p><div class="example-contents"><pre class="programlisting">DocumentResult dr = <span class="ReservedWord">new</span> DocumentResult();
marshaller.marshal( object, dr );
o = dr.getDocument();</pre></div></div><br class="example-break"><p>Similar mechanism is available for JDOM and XOM. This conversion
        is much more efficient than first marshalling to
        <code class="literal">ByteArrayOutputStream</code> and then read it back into these
        DOMs. The same mechanism can be used to marshal to <a class="link" href="http://fi.java.net/" target="_top">FastInfoset</a> or send the
        marshaled document to an XSLT engine (<code class="literal">TransformerHandler</code>.)</p><p>The other interesting connector is <code class="literal">JAXBSource</code>,
        which wraps a marshaller and allows a JAXB object to be used as a
        "source" of XML. Many XML APIs take <code class="literal">Source</code> as an input,
        and now JAXB object can be passed to them directly.</p><p>For example, you can marshal a JAXB object and unmarshal it into
        another JAXBContext like this:</p><div class="example"><a name="d0e3567"></a><p class="title"><b>Example&nbsp;82.&nbsp;Loading into a different JAXBContext</b></p><div class="example-contents"><pre class="programlisting">JAXBContext context1 = ... ;
JAXBContext context2 = ... ;

context1.createUnmarshaller().unmarshal( <span class="ReservedWord">new</span> JAXBSource(context2,object) );</pre></div></div><br class="example-break"><p>This amounts to looking at the same XML by using different
        schema, and again this is much more efficient than going through
        <code class="literal">ByteArrayOutputStream</code>.</p></div></div><div lang="en" class="section" title="5.4.&nbsp;Interaction between marshalling and DOM"><div class="titlepage"><div><div><h3 class="title" id="marshalling-interaction-between-marshalling-and-dom">5.4.&nbsp;Interaction between marshalling and DOM</h3></div></div></div><p>Sometimes you may notice that JAXB is producing XML with seemingly
    unnecessary namespace declarations. In this section, we'll discuss the
    possible causes and how to resolve this.</p><div class="section" title="5.4.1.&nbsp;Caused by DOM mapping"><div class="titlepage"><div><div><h4 class="title" id="Caused_by_DOM_mapping">5.4.1.&nbsp;Caused by DOM mapping</h4></div></div></div><p>The #1 cause of extra namespace declarations is due to the DOM
        mapping. This mainly happens because of a schema construct that forces
        XJC to generate a property with DOM. This includes the use of wildcard
        <code class="literal">&lt;xs:any/&gt;</code> (see more about this <a class="xref" href="ch03.html#compiling-xml-schema-mapping-of-xs-any" title="1.3.&nbsp;Mapping of <xs:any /&gt;">Mapping of <code class="literal">&lt;xs:any /&gt;</code></a>), as well as <code class="literal">xs:anyType</code>
        (which can also happen by omission, such as <code class="literal">&lt;xs:element
        name="foo"/&gt;</code>, which is interpreted as <code class="literal">&lt;xs:element
        name="foo" type="xs:anyType" /&gt;</code>.</p><p>During unmarshalling, when a subtree of the input XML is
        converted into XML, JAXB copies all the in-scope namespace bindings
        active at that time to the root of the DOM element. So for example,
        given the following Java class and XML, the DOM tree that the
        <code class="literal">child</code> field will get will look like the following:</p><div class="example"><a name="d0e3607"></a><p class="title"><b>Example&nbsp;83.&nbsp;Bean with wildcard</b></p><div class="example-contents"><pre class="programlisting"><span class="Annotation">@XmlRootElement</span>
<span class="ReservedWord">class</span> Foo {
  <span class="Annotation">@XmlAnyElement</span>
  <span class="ReservedWord">public</span> Element child;
}</pre></div></div><br class="example-break"><div class="example"><a name="d0e3612"></a><p class="title"><b>Example&nbsp;84.&nbsp;Instance with subtree matching wildcard</b></p><div class="example-contents"><pre class="programlisting"><span class="ReservedWord">&lt;foo</span> <span class="Identifier">xmlns:a</span>=<span class="String">"a"</span> <span class="Identifier">xmlns:b</span>=<span class="String">"b"</span> <span class="Identifier">xmlns:c</span>=<span class="String">"c"</span><span class="ReservedWord">&gt;</span>
  <span class="ReservedWord">&lt;subtree</span> <span class="Identifier">xmlns:c</span>=<span class="String">"cc"</span><span class="ReservedWord">&gt;</span>
    <span class="ReservedWord">&lt;data&gt;</span>a:xyz<span class="ReservedWord">&lt;/data&gt;</span>
  <span class="ReservedWord">&lt;/subtree&gt;</span>
<span class="ReservedWord">&lt;/foo&gt;</span></pre></div></div><br class="example-break"><div class="example"><a name="d0e3617"></a><p class="title"><b>Example&nbsp;85.&nbsp;DOM tree to be stored in Foo.child</b></p><div class="example-contents"><pre class="programlisting"><span class="ReservedWord">&lt;subtree</span> <span class="Identifier">xmlns:a</span>=<span class="String">"a"</span> <span class="Identifier">xmlns:b</span>=<span class="String">"b"</span> <span class="Identifier">xmlns:c</span>=<span class="String">"cc"</span><span class="ReservedWord">&gt;</span>
    <span class="ReservedWord">&lt;data&gt;</span>a:xyz<span class="ReservedWord">&lt;/data&gt;</span>
  <span class="ReservedWord">&lt;/subtree&gt;</span></pre></div></div><br class="example-break"><p>Note that the two namespace declarations are copied over, but
        <code class="literal">c</code> is not because it's overridden. Also not that JAXB is
        not touching the whitespace in document. This copying of namespace
        declarations is necessary to preserve the infoset in the input
        document. For example, if the <code class="literal">&lt;data&gt;</code> is a QName, its meaning
        would change if JAXB unmarshaller doesn't copy it.</p><p>Now, imagine what happens when you marshal this back to XML.
        Despite the fact that in this example neither <code class="literal">b</code> nor
        <code class="literal">c</code> prefixes are in use, JAXB cannot delete them, because
        it doesn't know if those attributes are significant to the application
        or not. Therefore, this could end up producing XML with "extra
        namespace declarations" like:</p><div class="example"><a name="d0e3638"></a><p class="title"><b>Example&nbsp;86.&nbsp;DOM tree to be stored in Foo.child</b></p><div class="example-contents"><pre class="programlisting"><span class="ReservedWord">&lt;foo&gt;</span>
  <span class="ReservedWord">&lt;subtree</span> <span class="Identifier">xmlns:a</span>=<span class="String">"a"</span> <span class="Identifier">xmlns:b</span>=<span class="String">"b"</span> <span class="Identifier">xmlns:c</span>=<span class="String">"cc"</span><span class="ReservedWord">&gt;</span>
    <span class="ReservedWord">&lt;data&gt;</span>a:xyz<span class="ReservedWord">&lt;/data&gt;</span>
  <span class="ReservedWord">&lt;/subtree&gt;</span>
<span class="ReservedWord">&lt;/foo&gt;</span></pre></div></div><br class="example-break"><p>Resolving this problem is not possible in the general case, but
        sometimes one of the following strategy works:</p><div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem"><p>Sometimes schema author incorrectly assumes that
                <code class="literal">&lt;xs:element name="foo"/&gt;</code> means
                <code class="literal">&lt;xs:element name="foo" type="xs:string"/&gt;</code>,
                because attribute declarations work somewhat like this. In
                such a case, adding explicit <code class="literal">type</code> attribute
                avoids the use of DOM, so things will work as expected.</p></li><li class="listitem"><p>The wildcard processing mode " <code class="literal">strict</code>"
                would force a typed binding, and thereby eliminate any DOM
                mapping.</p></li><li class="listitem"><p>You might be able to manulally go into the DOM tree and
                remove unnecessary namespace declarations, if your application
                knows what are necessary and what are not.</p></li></ol></div></div></div></div><div lang="en" class="section" title="6.&nbsp;Schema Generation"><div class="titlepage"><div><div><h2 class="title" style="clear: both" id="schema-generation">6.&nbsp;Schema Generation</h2></div></div></div><div lang="en" class="section" title="6.1.&nbsp;Invoking schemagen programatically"><div class="titlepage"><div><div><h3 class="title" id="schema-generation-invoking-schemagen-programatically">6.1.&nbsp;Invoking schemagen programatically</h3></div></div></div><p>Schemagen tools by default come in as CLI, ant task, and Maven
    plugin. These interfaces allow you to invoke schemagen functionality from
    your program.</p><div class="section" title="6.1.1.&nbsp;At runtime"><div class="titlepage"><div><div><h4 class="title" id="At_runtime">6.1.1.&nbsp;At runtime</h4></div></div></div><p>If the classes you'd like to generate schema from are already
        available as <code class="literal">java.lang.Class</code> objects (meaning they are
        already loaded and resolved in the current JVM), then the easiest way
        to generate a schema is to use the JAXB API:</p><div class="example"><a name="d0e3685"></a><p class="title"><b>Example&nbsp;87.&nbsp;Generate schema at runtime</b></p><div class="example-contents"><pre class="programlisting">File baseDir = <span class="ReservedWord">new</span> File(<span class="String">"."</span>);

<span class="ReservedWord">class</span> MySchemaOutputResolver <span class="ReservedWord">extends</span> SchemaOutputResolver {
    <span class="ReservedWord">public</span> Result createOutput( String namespaceUri, String suggestedFileName ) <span class="ReservedWord">throws</span> IOException {
        <span class="ReservedWord">return</span> <span class="ReservedWord">new</span> StreamResult(<span class="ReservedWord">new</span> File(baseDir,suggestedFileName));
    }
}

JAXBContext context = JAXBContext.newInstance(Foo.<span class="ReservedWord">class</span>, Bar.<span class="ReservedWord">class</span>, ...);
context.generateSchema(<span class="ReservedWord">new</span> MySchemaOutputResolver());</pre></div></div><br class="example-break"></div><div class="section" title="6.1.2.&nbsp;CLI interface"><div class="titlepage"><div><div><h4 class="title" id="CLI_interface">6.1.2.&nbsp;CLI interface</h4></div></div></div><p>The <a class="link" href="http://fisheye5.cenqua.com/browse/jaxb2-sources/jaxb-ri/xjc/src/com/sun/tools/jxc/SchemaGenerator.java?r=jaxb-2_1-branch" target="_top">CLI
        interface (<code class="code">public static int
        com.sun.tools.jxc.SchemaGenerator.run(String[])</code>)</a> is the
        easiest API to access. You can pass in all the schemagen command-line
        arguments as a string array, and get the exit code as an int value.
        Messages are sent to <code class="literal">System.err</code> and
        <code class="literal">System.out</code>.</p></div><div class="section" title="6.1.3.&nbsp;Ant interface"><div class="titlepage"><div><div><h4 class="title" id="Ant_interface">6.1.3.&nbsp;Ant interface</h4></div></div></div><p>Ant task can be invoked very easily from a non-Ant program. The
        schemagen ant task is defined in <a class="link" href="http://fisheye5.cenqua.com/browse/jaxb2-sources/jaxb-ri/xjc/facade/com/sun/tools/jxc/SchemaGenTask.java?r=jaxb-2_1-branch" target="_top">the
        SchemaGenTask class</a>,</p><p>For more about invoking an Ant task programatically, see the
        article <a class="link" href="http://www.fawcette.com/javapro/2004_06/magazine/features/kgauthier/" target="_top">"Keep
        the Ant, Hold the XML"</a>.</p></div><div class="section" title="6.1.4.&nbsp;Native Java API"><div class="titlepage"><div><div><h4 class="title" id="Native_Java_API">6.1.4.&nbsp;Native Java API</h4></div></div></div><p>The above two interfaces are built on top of externally
        committed contracts, so they'll evolve only in a compatibile way. The
        downside is that the amount of control you can exercise over them
        would be limited.</p><p>So yet another approach to invoke schemagen is to use JAXB RI's
        internal interfaces. But be warned that those interfaces are subject
        to change in the future versions, despite our best effort to preserve
        them. This is the API that the JAX-WS RI uses to generate schema
        inside WSDL when they generate WSDL, so does some other web services
        toolkits that work with the JAXB RI.</p><p>Most of those interfaces are defined and well-documented in
        <a class="link" href="http://fisheye5.cenqua.com/browse/jaxb2-sources/jaxb-ri/xjc/src/com/sun/tools/xjc/api" target="_top">the
        com.sun.tools.xjc.api package</a>. You can see how the schemagen
        tools are eventually calling into this API at <a class="link" href="http://fisheye5.cenqua.com/browse/jaxb2-sources/jaxb-ri/xjc/src/com/sun/tools/jxc/apt/SchemaGenerator.java?r=jaxb-2_1-branch" target="_top">the
        implementaion of SchemaGenerator class</a>.</p></div></div><div lang="en" class="section" title="6.2.&nbsp;Generating Schema that you want"><div class="titlepage"><div><div><h3 class="title" id="schema-generation-generating-schema-that-you-want">6.2.&nbsp;Generating Schema that you want</h3></div></div></div><p>This section discusses how you can change the generated XML schema.
    For changes that also affect the infoset (such as changing elements to
    attributes, namespaces, etc.), refer to a different section " <a class="link" href="http://jaxb.java.net/guide/annotating-your-classes-xml-layout-and-in-memory-data-layout" target="_top">XML
    layout and in-memory data layout</a>."</p><div class="section" title="6.2.1.&nbsp;Adding facets to datatypes"><div class="titlepage"><div><div><h4 class="title" id="Adding_facets_to_datatypes">6.2.1.&nbsp;Adding facets to datatypes</h4></div></div></div><p>As of JAXB 2.1.4, currently no support for this, although there
        has been <a class="link" href="http://www.nabble.com/forum/Search.jtp?query=facet&amp;local=y&amp;forum=13500&amp;daterange=0&amp;startdate=&amp;enddate=" target="_top">several
        discussions in the users alias</a>.</p><p>The JAXB project is currently lacking resources to attack this
        problem, and therefore looking for volunteers to work on this project.
        The basic idea would be to define enough annotations to cover the
        basic constraint facets (such as length, enumerations, pattern, etc.)
        The schema generator would have to be then extended to honor those
        annotations and generate schemas accordingly.</p><p>Some users pointed out relevance of this to <a class="link" href="http://jcp.org/en/jsr/detail?id=303" target="_top">JSR 303: Bean
        Validation</a>. If you are interested in picking up this task, let
        us know!</p></div></div></div><div lang="en" class="section" title="7.&nbsp;Deployment"><div class="titlepage"><div><div><h2 class="title" style="clear: both" id="deployment">7.&nbsp;Deployment</h2></div></div></div><div lang="en" class="section" title="7.1.&nbsp;Migrating JAXB 2.0 applications to JavaSE 6"><div class="titlepage"><div><div><h3 class="title" id="deployment-migrating-jaxb-2-0-applications-to-javase-6">7.1.&nbsp;Migrating JAXB 2.0 applications to JavaSE 6</h3></div></div></div><p>JavaSE 6 ships with its own JAXB 2.0 implementation. This
    implementation is based on the JAXB RI, where the only differences
    are:</p><div class="itemizedlist"><ul class="itemizedlist" type="disc"><li class="listitem"><p><span class="bold"><strong>No RI-specific vendor extensions are
            supported:</strong></span> This is so that portability across different
            JavaSE 6 implementations will be guaranteed.</p></li><li class="listitem"><p><span class="bold"><strong>Code in JavaSE 6 is hosted in its own
            packages to avoid conflicts:</strong></span> This allows applications
            to continue to use a specific version of the JAXB RI that they
            choose to use.</p></li></ul></div><p>Therefore, if you develop an application that uses JAXB 2.0 for
    JavaSE 5 today, the easiest way to upgrade to JavaSE 6 is to do nothing.
    You should keep the JAXB RI in your development environment, keep bundling
    the JAXB RI runtime jars to your app, just like you do that today.</p><div class="section" title="7.1.1.&nbsp;Reducing footprint"><div class="titlepage"><div><div><h4 class="title" id="Reducing_footprint">7.1.1.&nbsp;Reducing footprint</h4></div></div></div><p>If you'd like to reduce the footprint of your application by
        taking advantage of a JAXB implementation in JavaSE, you can take
        the following steps:</p><div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem"><p>You will no longer have to ship
                <code class="filename">jaxb-api.jar</code> in your application. This doesn't
                require any change to your code.</p></li><li class="listitem"><p>If your application does not use any of the vendor
                extension features of the JAXB RI runtime (such as
                unmarshaller/marshaller properties whose names start with
                "<code class="literal">com.sun.</code>"), then you will no longer have to ship
                <code class="filename">jaxb-impl.jar</code> (nor <code class="filename">jaxb1-impl.jar</code>,
                <code class="filename">jaxb-libs.jar</code>.) When you do this, be sure to test
                your application since it's not very easy to find all such
                dependencies.</p></li></ol></div></div><div class="section" title="7.1.2.&nbsp;Using JAXB with Java SE"><div class="titlepage"><div><div><h4 class="title" id="Using_JAXB_with_JavaSE">7.1.2.&nbsp;Using JAXB with Java SE</h4></div></div></div><p>JavaSE comes with JAXB 2.x API/implementation in <code class="literal">rt.jar</code>. Each 
        version of JavaSE (6, 7, 8, ...) contains different version of JAXB 2.x 
        API. Therefore, if you want to use different version of JAXB API/implementation 
        than the one present in your version of JDK, you are required to override 
        a portion of <code class="literal">rt.jar</code> with the new API. There are 
        several ways to achieve this:</p><div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem"><p>Place the <code class="filename">jaxb-api.jar</code> into
                <code class="code">$JRE_HOME/lib/endorsed</code> and put jaxb-impl to classpath
                of your application.
                Do not put jaxb-impl or jaxb-xjc into the endorsed directory.
                This essentially makes your JRE to "JRE X + JAXB 2.y". This won't 
                affect any other applications that use this JRE, and it's easy. 
                On the other hand, in various scenarios you may not be able to 
                alter the JRE.</p></li><li class="listitem"><p>Use the system property <code class="literal">java.endorsed.dirs</code>
                when you launch your application, and have it point to the
                directory which contains the <code class="filename">jaxb-api.jar</code> only. The 
                directory must not contain any other jaxb artifacts 
                (like jaxb-impl.jar or jaxb-xjc.jar). This allows you use to use 
                different version of JAXB without modifying the JRE.</p></li></ol></div><p>No matter which approach you take, make sure not to include jar
        files other than <code class="filename">jaxb-api.jar</code>. Doing so, for example
        including <code class="filename">jaxb-xjc.jar</code>, may result in classloading
        related errors such as "taskdef A class needed by class
        com.sun.tools.xjc.XJCTask cannot be found:
        org/apache/tools/ant/...."</p><p>See <a class="link" href="http://docs.oracle.com/javase/6/docs/technotes/guides/standards/" target="_top">the
        endorsed directory mechanism</a> for more details.</p></div><div class="section" title="7.1.3.&nbsp;Where's the XJC ant task?"><div class="titlepage"><div><div><h4 class="title" id="Where_s_the_XJC_ant_task_">7.1.3.&nbsp;Where's the XJC ant task?</h4></div></div></div><p>JavaSE has never shipped an Ant task implementation, so we are
        just following that tradition. There's an (process-wise) overhead of
        adding additional dependencies during the JavaSE build, and there
        would likely be some runtime dependency issues in having a class in
        <code class="literal">tools.jar</code> that would require the ant classes, due to
        class loader delegation.</p><p>We are thinking about perhaps releasing a small jar that only
        contains the ant task for JDK6.</p><p>Please also note that the syntax of <code class="literal">&lt;xjc&gt;</code> task is neither
        defined in the JAXB spec nor in the JavaSE spec. Therefore other
        JavaSE vendors may not implement that at all, or do so in a different
        class name, etc. Therefore, from a portability perspective, if you
        choose to depend on the <code class="literal">&lt;xjc&gt;</code> task you should bundle the JAXB
        RI.</p></div></div><div lang="en" class="section" title="7.2.&nbsp;Which JAXB RI is included in which JDK?"><div class="titlepage"><div><div><h3 class="title" id="deployment-which-jaxb-ri-is-included-in-which-jdk">7.2.&nbsp;Which JAXB RI is included in which JDK?</h3></div></div></div><p>This table captures the history of the JAXB RI integration into JDK.
    This is for information purposes only. In particular, the JAXB RI in JDK
    is package renamed to avoid any conflict with the stand-alone JAXB RI
    distribution or with the jaxb2-reflection library. You can use any version
    of these with any version of JDK without worrying about implementation
    conflicts.</p><div class="informaltable"><table border="1"><colgroup><col width="50%"><col width="50%"></colgroup><tbody><tr><td><p>JDK6 first release - JDK6 u3</p></td><td><a class="link" href="/2.0.3/" target="_top">JAXB RI
                    2.0.3</a></td></tr><tr><td><p>JDK6 u4</p></td><td><a class="link" href="/2.1.3/" target="_top">JAXB RI
                    2.1.3</a></td></tr><tr><td><p>JDK6 u14</p></td><td><a class="link" href="/2.1.10/" target="_top">JAXB RI
                    2.1.10</a></td></tr><tr><td><p>JDK7 first release</p></td><td><a class="link" href="/2.2.4-1/" target="_top">JAXB RI
                    2.2.4-1</a></td></tr></tbody></table></div></div><div lang="en" class="section" title="7.3.&nbsp;Running JAXB 1.0 and 2.x side by side"><div class="titlepage"><div><div><h3 class="title" id="deployment-running-jaxb-1-0-and-2-x-side-by-side">7.3.&nbsp;Running JAXB 1.0 and 2.x side by side</h3></div></div></div><p>You should still be able to use the legacy compatible jaxb1-impl.jar: 
    <code class="filename">http://search.maven.org/remotecontent?filepath=com/sun/xml/bind/jaxb1-impl/2.2.5-1/jaxb1-impl-2.2.5-1.jar</code>
    with your application. Note however that this jar is no longer distributed with JAXB 2.2.x releases and this 
    functionality is no longer supported.
    </p></div><div lang="en" class="section" title="7.4.&nbsp;Migrating JAXB 1.0 applications to JAXB 2.x"><div class="titlepage"><div><div><h3 class="title" id="deployment-migrating-jaxb-1-0-applications-to-jaxb-2-x">7.4.&nbsp;Migrating JAXB 1.0 applications to JAXB 2.x</h3></div></div></div><p>While it's always possible to keep your JAXB 1.0 applications as-is
    and run them on the JAXB 2.x runtime, or have some parts of your
    application use JAXB 1.0 while others use 2.x, there are situations where
    you might prefer to migrate your existing applications from JAXB 1.0 to
    JAXB 2.x.</p><p>Common reasons why people would like to migrate includes:</p><div class="itemizedlist"><ul class="itemizedlist" type="disc"><li class="listitem"><p>Taking advantage of the flexible, robust unmarshalling in
            JAXB 2.0</p></li><li class="listitem"><p>Exposing the JAXB-bound objects through JAX-WS as web
            services</p></li></ul></div><div class="section" title="7.4.1.&nbsp;Typical migration work"><div class="titlepage"><div><div><h4 class="title" id="Typical_migration_work">7.4.1.&nbsp;Typical migration work</h4></div></div></div><p>This section outlines how the typical migration work
        proceeds:</p><div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem"><p>Replace the invocation of XJC 1.0.x with XJC 2.x. Both
                the CLI and ant task syntax are backward-compatible to make
                this easier.</p></li><li class="listitem"><p>Re-compile your schema with XJC 2.x. This will generate
                a new and different set of classes and methods.</p></li><li class="listitem"><p>Update your application code that deals with the
                generated code to use the newer classes and methods. This step
                is mostly straight-forward but may be time consuming,
                especially if your project is big.</p></li><li class="listitem"><p>Remove the JAXB 1.0.x runtime from your application, and
                place in JAXB 2.x runtime instead. See the list for <a class="link" href="http://java.sun.com/webservices/docs/1.5/jaxb/ReleaseNotes.html" target="_top">what
                jars were used in 1.0</a> and <a class="link" href="http://jaxb.java.net/nonav/2.1.3/docs/ReleaseNotes.html" target="_top">what
                are used in 2.0</a>.</p></li></ol></div><p>The classes generated from JAXB 2.x tends to be <a class="link" href="http://weblogs.java.net/blog/kohsuke/archive/2005/08/a_story_of_migr.html" target="_top">a
        lot more compact</a>.</p><p>JAXB RI 2.x ships many of the same samples that JAXB RI 1.0.x
        shipped, except that they are updated to work with JAXB 2.0. So
        comparing those samples may help you better understand what this type
        of migration involves.</p></div><div class="section" title="7.4.2.&nbsp;Other Miscellaneous Notes"><div class="titlepage"><div><div><h4 class="title" id="Other_Miscellaneous_Notes">7.4.2.&nbsp;Other Miscellaneous Notes</h4></div></div></div><div class="itemizedlist"><ul class="itemizedlist" type="disc"><li class="listitem"><p>JAXB 2.x requires JavaSE 5 or above, whereas JAXB 1.0
                runs on JavaSE 1.3 or above.</p></li><li class="listitem"><p>The <code class="literal">javax.xml.bind</code> interfaces remain the
                same. So the part of the code that deals with those interfaces
                may remain the same.</p></li><li class="listitem"><p>JAXB 1.0 unmarshaller was a lot more draconian to the
                errors in the input document than 2.0 is. In a sense, you can
                think of the 1.0 unmarshaller as equivalent to the 2.0
                unmarshaller + validator. If your application was relying on
                this behaivior, you may want to enable validation in 2.0 by
                using <code class="literal">Unmarshaller.setSchema</code>.</p></li><li class="listitem"><p>JAXB 2.x by default creates plain Java beans, whereas in
                1.0 it created separated interfaces and implementations. Many
                people find beans to be easier to work with, but you can use
                the following customization to tell JAXB 2.x to generate
                interfaces and implementations in a similar fashion. </p><div class="example"><a name="d0e3984"></a><p class="title"><b>Example&nbsp;88.&nbsp;Interface/Implementation customization</b></p><div class="example-contents"><pre class="programlisting"><span class="ReservedWord">&lt;jxb:bindings</span> <span class="Identifier">version</span>=<span class="String">"2.1"</span>
              <span class="Identifier">xmlns:jxb</span>=<span class="String">"http://java.sun.com/xml/ns/jaxb"</span><span class="ReservedWord">&gt;</span>
  <span class="ReservedWord">&lt;jxb:globalBindings</span> <span class="Identifier">generateValueClass</span>=<span class="String">"false"</span><span class="ReservedWord"> /&gt;</span>
<span class="ReservedWord">&lt;/jxb:bindings&gt;</span></pre></div></div><p><br class="example-break"></p></li><li class="listitem"><p>When creating instances of the generated classes, JAXB
                1.0 required that you do so through
                <code class="literal">ObjectFactory</code>, like <code class="code">new
                ObjectFactory().createAbc()</code>. With 2.0, you can simply
                do <code class="code">new Abc()</code>. This no longer throws
                <code class="literal">JAXBException</code>s, either.</p></li><li class="listitem"><p>Binding customization syntax of 2.0 is backward
                compatible with 1.0. However, there are several customizations
                that were previously allowed in 1.0 but not in 2.0, such as
                using class customizations on model groups.</p></li></ul></div></div></div><div lang="en" class="section" title="7.5.&nbsp;Runtime Errors"><div class="titlepage"><div><div><h3 class="title" id="deployment-runtime-errors">7.5.&nbsp;Runtime Errors</h3></div></div></div><div class="section" title="7.5.1.&nbsp;Illegal class modifiers for package-info: 0x1600"><div class="titlepage"><div><div><h4 class="title" id="Illegal_class_modifiers_for_package_info__0x1600">7.5.1.&nbsp;Illegal class modifiers for package-info: 0x1600</h4></div></div></div><p>When you compile your sources files with JDK from Java6 and try
        to run it on Java5 JVMs, you may see a <code class="literal">ClassFormatError</code>
        at runtime like this:</p><div class="informalexample"><pre class="programlisting">main" java.lang.ClassFormatError: Illegal class modifiers in class
com/alu/parentalcontrol/jaxb/package-info: 0x1600
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:620)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:260)
at java.net.URLClassLoader.access$100(URLClassLoader.java:56)
at java.net.URLClassLoader$1.run(URLClassLoader.java:195)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:268)
at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:242)
at java.lang.Package.getPackageInfo(Package.java:350)
at java.lang.Package.getAnnotation(Package.java:361)
at com.sun.xml.bind.v2.model.annotation.RuntimeInlineAnnotationReader.getPackageAnnotation(RuntimeInlineAnnotationReader.java:125)
at com.sun.xml.bind.v2.model.annotation.RuntimeInlineAnnotationReader.getPackageAnnotation(RuntimeInlineAnnotationReader.java:53)
at com.sun.xml.bind.v2.model.impl.TypeInfoImpl.parseElementName(TypeInfoImpl.java:122)
at com.sun.xml.bind.v2.model.impl.ClassInfoImpl.&lt;init&gt;(ClassInfoImpl.java:166)</pre></div><p>This is due to a bug, and so far the only way to fix this is to
        compile your project with JavaSE 5.</p><p>Here is what's happening. Java5 added a new class file modifier
        attribute called <code class="literal">ACC_SYNTHETIC</code>, whose bit value is
        0x1000. This attribute marks types and methods that are not present in
        the source file but generated by the compiler. When
        <code class="filename">package-info.java</code> is compiled into
        <code class="filename">package-info.class</code>, javac in Java5 apparently only put
        0x0600 (= <code class="code">ACC_ABSTRACT|ACC_INTERFACE</code>.) Some time during
        Java6 development, someone filed <a class="link" href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6232928" target="_top">a
        bug, saying it should also include <code class="literal">ACC_SYNTHETIC</code>
        bit</a>, since it was a synthesized class.</p><p>Later <a class="link" href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6313196" target="_top">it
        is discovered that the corresponding VM change needs to be made to
        allow this 0x1600 combination</a>, but apparently no one realized
        the real implication of this --- namely, 0x1600 will break all the
        past JVMs. Of course, this problem is <a class="link" href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6553734" target="_top">eventually
        discovered</a>, but as of this writing there's still no fix for
        this.</p><p>So as you see, this is why the only workaround is to use javac
        from Java5.</p></div></div></div><div lang="en" class="section" title="8.&nbsp;Other Miscellaneous Topics"><div class="titlepage"><div><div><h2 class="title" style="clear: both" id="other-miscellaneous-topics">8.&nbsp;Other Miscellaneous Topics</h2></div></div></div><div lang="en" class="section" title="8.1.&nbsp;Performance and thread-safety"><div class="titlepage"><div><div><h3 class="title" id="other-miscellaneous-topics-performance-and-thread-safety">8.1.&nbsp;Performance and thread-safety</h3></div></div></div><p>The JAXBContext class is thread safe, but the Marshaller,
    Unmarshaller, and Validator classes are not thread safe.</p><p>For example, suppose you have a multi-thread server application that
    processes incoming XML documents by JAXB. In this case, for the best
    performance you should have just one instance of JAXBContext in your whole
    application like this:</p><div class="example"><a name="d0e4066"></a><p class="title"><b>Example&nbsp;89.&nbsp;Singleton JAXBContext</b></p><div class="example-contents"><pre class="programlisting"><span class="ReservedWord">class</span> MyServlet <span class="ReservedWord">extends</span> HttpServlet {
    <span class="ReservedWord">static</span> <span class="ReservedWord">final</span> JAXBContext context = initContext();

    <span class="ReservedWord">private</span> <span class="ReservedWord">static</span> JAXBContext initContext() {
        <span class="ReservedWord">return</span> JAXBContext.newInstance(Foo.<span class="ReservedWord">class</span>,Bar.<span class="ReservedWord">class</span>);
    }
}</pre></div></div><br class="example-break"><p>And each time you need to unmarshal/marshal/validate a document.
    Just create a new Unmarshaller/Marshaller/Validator from this context,
    like this:</p><div class="example"><a name="d0e4073"></a><p class="title"><b>Example&nbsp;90.&nbsp;Thread local Unmarshaller</b></p><div class="example-contents"><pre class="programlisting">    <span class="ReservedWord">public</span> <span class="ReservedWord">void</span> doGet( HttpServletRequest req, HttpServletResponse ) {
        Unmarshaller u = context.createUnmarshaller();
        u.unmarshal(...);
    }</pre></div></div><br class="example-break"><p>This is the simplest safe way to use the JAXB RI from multi-threaded
    applications.</p><p>If you really care about the performance, and/or your application is
    going to read a lot of small documents, then creating Unmarshaller could
    be relatively an expensive operation. In that case, consider pooling
    Unmarshaller objects. Different threads may reuse one Unmarshaller
    instance, as long as you don't use one instance from two threads at the
    same time.</p></div><div lang="en" class="section" title="8.2.&nbsp;Compiling DTD"><div class="titlepage"><div><div><h3 class="title" id="other-miscellaneous-topics-compiling-dtd">8.2.&nbsp;Compiling DTD</h3></div></div></div><p>The JAXB RI is shipped with an "experimental" DTD support, which
    let's you compile XML DTDs. It is marked "experimental" not because the
    feature is unstable nor unreliable, but rather because it's not a part of
    the JAXB specification and therefore the level of commitment to
    compatibility is lower.</p><div class="example"><a name="d0e4088"></a><p class="title"><b>Example&nbsp;91.&nbsp;To compile a DTD, run the XJC binding compiler as
        follows:</b></p><div class="example-contents"><pre class="programlisting">$ xjc.sh -dtd test.dtd</pre></div></div><br class="example-break"><p>All the other command-line options of the XJC binding compiler can
    be applied. Similarly, the XJC ant task supports DTD. The generated code
    will be no different from what is generated from W3C XML Schema. You'll
    use the same JAXB API to access the generated code, and it is portable in
    the sense that it will run on any JAXB 2.0 implementation.</p><p>DTD long predates XML namespace, although people since then
    developed various techniques to use XML namespaces in conjunction with
    DTD. Because of this, XJC is currently unable to reverse-engineer the use
    of XML namespace from DTD. If you compile DTDs that use those techniques,
    you'd either manuallly modify the generated code, or you can try a tool
    like <a class="link" href="http://www.thaiopensource.com/relaxng/trang.html" target="_top">Trang</a>
    that can convert DTD into XML Schema in ways that better preserves XML
    namespaces.</p><div class="section" title="8.2.1.&nbsp;Customizations"><div class="titlepage"><div><div><h4 class="title" id="Customizations">8.2.1.&nbsp;Customizations</h4></div></div></div><p>The customization syntax for DTD is roughly based on the
        ver.0.21 working draft of the JAXB specification, which is available
        at <a class="link" href="http://xml.coverpages.org/jaxb0530spec.pdf" target="_top">xml.coverpages.org</a>.
        The deviations from this document are:</p><div class="itemizedlist"><ul class="itemizedlist" type="disc"><li class="listitem"><p>The <code class="literal">whitespace</code> attribute of the
                <code class="literal">conversion</code> element takes "
                <code class="literal">preserve</code>", " <code class="literal">replace</code>", and "
                <code class="literal">collapse</code>" instead of " <code class="literal">preserve</code>", "
                <code class="literal">normalize</code>", and " <code class="literal">collapse</code>" as
                specified in the document.</p></li><li class="listitem"><p>The <code class="literal">interface</code> customization just generates
                marker interfaces with no method.</p></li></ul></div></div><div class="section" title="8.2.2.&nbsp;Compiling DTD from Maven2"><div class="titlepage"><div><div><h4 class="title" id="Compiling_DTD_from_Maven2">8.2.2.&nbsp;Compiling DTD from Maven2</h4></div></div></div><div class="example"><a name="d0e4145"></a><p class="title"><b>Example&nbsp;92.&nbsp;The following POM snippest describes how to invoke XJC to
            compile DTD from a Maven 2 project:</b></p><div class="example-contents"><pre class="programlisting"><span class="ReservedWord">&lt;plugin&gt;</span>
  <span class="ReservedWord">&lt;groupId&gt;</span>org.jvnet.jaxb2.maven2<span class="ReservedWord">&lt;/groupId&gt;</span>
  <span class="ReservedWord">&lt;artifactId&gt;</span>maven-jaxb2-plugin<span class="ReservedWord">&lt;/artifactId&gt;</span>
  <span class="ReservedWord">&lt;executions&gt;</span>
    <span class="ReservedWord">&lt;execution&gt;</span>
      <span class="ReservedWord">&lt;goals&gt;</span>
        <span class="ReservedWord">&lt;goal&gt;</span>generate<span class="ReservedWord">&lt;/goal&gt;</span>
      <span class="ReservedWord">&lt;/goals&gt;</span>
      <span class="ReservedWord">&lt;configuration&gt;</span>
        <span class="Comment">&lt;!--  if you want to put DTD somewhere else
        &lt;schemaDirectory&gt;src/main/jaxb&lt;/schemaDirectory&gt;
        --&gt;</span>
        <span class="ReservedWord">&lt;extension&gt;</span>true<span class="ReservedWord">&lt;/extension&gt;</span>
        <span class="ReservedWord">&lt;schemaLanguage&gt;</span>DTD<span class="ReservedWord">&lt;/schemaLanguage&gt;</span>
        <span class="ReservedWord">&lt;schemaIncludes&gt;</span>
          <span class="ReservedWord">&lt;schemaInclude&gt;</span>*.dtd<span class="ReservedWord">&lt;/schemaInclude&gt;</span>
        <span class="ReservedWord">&lt;/schemaIncludes&gt;</span>
        <span class="ReservedWord">&lt;bindingIncludes&gt;</span>
          <span class="ReservedWord">&lt;bindingInclude&gt;</span>*.jaxb<span class="ReservedWord">&lt;/bindingInclude&gt;</span>
        <span class="ReservedWord">&lt;/bindingIncludes&gt;</span>
        <span class="ReservedWord">&lt;args&gt;</span>
          <span class="ReservedWord">&lt;arg&gt;</span>-Xinject-listener-code<span class="ReservedWord">&lt;/arg&gt;</span>
        <span class="ReservedWord">&lt;/args&gt;</span>
      <span class="ReservedWord">&lt;/configuration&gt;</span>
    <span class="ReservedWord">&lt;/execution&gt;</span>
  <span class="ReservedWord">&lt;/executions&gt;</span>
  <span class="ReservedWord">&lt;dependencies&gt;</span>
    <span class="ReservedWord">&lt;dependency&gt;</span>
      <span class="ReservedWord">&lt;groupId&gt;</span>org.jvnet.jaxb2-commons<span class="ReservedWord">&lt;/groupId&gt;</span>
      <span class="ReservedWord">&lt;artifactId&gt;</span>property-listener-injector<span class="ReservedWord">&lt;/artifactId&gt;</span>
      <span class="ReservedWord">&lt;version&gt;</span>1.0<span class="ReservedWord">&lt;/version&gt;</span>
    <span class="ReservedWord">&lt;/dependency&gt;</span>
  <span class="ReservedWord">&lt;/dependencies&gt;</span>
<span class="ReservedWord">&lt;/plugin&gt;</span></pre></div></div><br class="example-break"><div class="example"><a name="d0e4150"></a><p class="title"><b>Example&nbsp;93.&nbsp;The dependencies section inside the plugin element can be
            used to specify additional XJC plugins. If you'd like to use more
            recent version of the JAXB RI, you can specify a dependency to XJC
            here to do so, like this:</b></p><div class="example-contents"><pre class="programlisting"><span class="ReservedWord">&lt;dependency&gt;</span>
  <span class="ReservedWord">&lt;groupId&gt;</span>com.sun.xml.bind<span class="ReservedWord">&lt;/groupId&gt;</span>
  <span class="ReservedWord">&lt;artifactId&gt;</span>jaxb-xjc<span class="ReservedWord">&lt;/artifactId&gt;</span>
  <span class="ReservedWord">&lt;version&gt;</span>2.1.2<span class="ReservedWord">&lt;/version&gt;</span>
<span class="ReservedWord">&lt;/dependency&gt;</span></pre></div></div><br class="example-break"><p>The complete sample project is available from <a class="link" href="http://weblogs.java.net/blog/kohsuke/archive/20070130/dtd.zip" target="_top">here</a>.</p></div></div><div lang="en" class="section" title="8.3.&nbsp;Using JAXB from Maven"><div class="titlepage"><div><div><h3 class="title" id="other-miscellaneous-topics-using-jaxb-from-maven">8.3.&nbsp;Using JAXB from Maven</h3></div></div></div><div class="example"><a name="d0e4164"></a><p class="title"><b>Example&nbsp;94.&nbsp;If you are using Maven 2 as your build system, you can declare
        the following dependencies in your POM for using the JAXB RI. Replace
        the version with the version of your choice.</b></p><div class="example-contents"><pre class="programlisting"><span class="ReservedWord">&lt;dependency&gt;</span>
  <span class="ReservedWord">&lt;groupId&gt;</span>com.sun.xml.bind<span class="ReservedWord">&lt;/groupId&gt;</span>
  <span class="ReservedWord">&lt;artifactId&gt;</span>jaxb-impl<span class="ReservedWord">&lt;/artifactId&gt;</span>
  <span class="ReservedWord">&lt;version&gt;</span>&amp;jaxb.release.impl.version;<span class="ReservedWord">&lt;/version&gt;</span>
<span class="ReservedWord">&lt;/dependency&gt;</span></pre></div></div><br class="example-break"><p>This artifact is available in <a class="link" href="http://maven-repository.java.net/" target="_top">the java.net Maven
    repository</a>, so you also need the following <code class="literal">&lt;repository&gt;</code>
    declaration in your POM:</p><div class="informalexample"><pre class="programlisting"><span class="ReservedWord">&lt;repository&gt;</span>
  <span class="ReservedWord">&lt;id&gt;</span>java.net<span class="ReservedWord">&lt;/id&gt;</span>
  <span class="ReservedWord">&lt;url&gt;</span>https://maven.java.net/content/repositories/releases/<span class="ReservedWord">&lt;/url&gt;</span>
  <span class="ReservedWord">&lt;layout&gt;</span>default<span class="ReservedWord">&lt;/layout&gt;</span>
<span class="ReservedWord">&lt;/repository&gt;</span></pre></div><p>For a list of available artifacts and versions, see <a class="link" href="https://maven.java.net/content/repositories/releases/com/sun/xml/bind/" target="_top">this</a>.
    In addition to the runtime jar, XJC is available under the artifact Id
    "<code class="literal">jaxb-xjc</code>".</p><p>You can also invoke XJC through a Maven plugin by using <a class="link" href="https://maven-jaxb2-plugin.java.net/" target="_top">the Maven2 JAXB 2.x
    plugin</a>.</p></div><div lang="en" class="section" title="8.4.&nbsp;Designing a client/server protocol in XML"><div class="titlepage"><div><div><h3 class="title" id="other-miscellaneous-topics-designing-a-client-server-protocol-in-xml">8.4.&nbsp;Designing a client/server protocol in XML</h3></div></div></div><p>Occasionally, people try to define a custom protocol that allows
    multiple XML requests/responses to be sent over a single transport channel
    (<a class="link" href="http://forums.java.net/jive/thread.jspa?threadID=27577" target="_top">example</a>.)
    This section discusses the non-trivial interaction between XML and
    sockets, and how you can design a protocol correctly.</p><p>XML1.0 requires a conforming parser to read the entire data till end
    of the stream (because a parser needs to handle documents like
    <code class="literal">&lt;root/&gt;&lt;!-- post root comment --&gt;</code>). As a result,
    a naive attempt to keep one <code class="literal">OutputStream</code> open and marshal
    objects multiple times fails.</p><div class="example"><a name="d0e4210"></a><p class="title"><b>Example&nbsp;95.&nbsp;One easy way to work around this limitation is to design your
        protocol so that the data on the wire will look like the
        following:</b></p><div class="example-contents"><pre class="programlisting"><span class="ReservedWord">&lt;conversation&gt;</span>
  <span class="Comment">&lt;!-- message 1 --&gt;</span>
  <span class="ReservedWord">&lt;message&gt;</span>
    ...
  <span class="ReservedWord">&lt;/message&gt;</span>

  <span class="Comment">&lt;!-- message 2 --&gt;</span>
  <span class="ReservedWord">&lt;message&gt;</span>
    ...
  <span class="ReservedWord">&lt;/message&gt;</span>

  ...
<span class="ReservedWord">&lt;/conversation&gt;</span></pre></div></div><br class="example-break"><p>The <code class="literal">&lt;conversation&gt;</code> start tag is sent immediately after the
    socket is opened. This works as a container to send multiple "messages",
    and this is also an excellent opportunity to do the hand-shaking (e.g.,
    <code class="literal">protocol-version='1.0'</code> attribute.) Once the
    <code class="literal">&lt;conversation&gt;</code> tag is written, multiple messages can be marshalled
    as a tree into the channel, possibly with a large time lag in between. You
    can use the JAXB marshaller to produce such message. When the sender wants
    to disconnect the channel, it can do so by sending the
    <code class="literal">&lt;/conversation&gt;</code> end tag, followed by the socket
    disconnection.</p><p>Of course, you can choose any tag names freely, and each message can
    have different tag names.</p><p>The receiver would use the StAX API and use
    <code class="literal">XMLStreamReader</code> to read this stream. You'd have to use this
    to process the first <code class="literal">&lt;conversation&gt;</code> start tag. After that, every
    time you call a JAXB unmarshaller, you'll get the next message.</p><p>For the concrete code, see the <code class="literal">xml-channel</code> example in
    the JAXB RI distribution.</p></div><div lang="en" class="section" title="8.5.&nbsp;Contributing to this Guide"><div class="titlepage"><div><div><h3 class="title" id="other-miscellaneous-topics-contributing-to-this-guide">8.5.&nbsp;Contributing to this Guide</h3></div></div></div><p>This document is maintained by people in the community. If you'd
    like to have the edit access to this document, please let us know so that
    we can discuss it.</p><p>The master source of this document is written in <a class="link" href="http://fisheye5.cenqua.com/browse/jaxb/unofficial-guide/docs" target="_top">HTML</a>
    + <a class="link" href="http://fisheye5.cenqua.com/browse/jaxb/unofficial-guide/tags" target="_top">a
    set of custom tags</a>. The use of custom tags allow us to ensure a
    consistent look&amp;feel, and take care of other mandane tasks like
    assigning chapter/section numbers and generating permalinks. The
    technology is based on <a class="link" href="http://commons.apache.org/jelly/" target="_top">Jelly</a>, so more custom
    tags can be added to perform additional processing and the possibility is
    endless.</p><p>Once you have the commit access, you can update the documents and
    run the build script to generate the final HTMLs to verify the result.
    When you feel satisfied, commit the changes. The repository is polled
    every hour, so your change will be eventually picked up and published, but
    you can also force the update by sending an e-mail to
    <code class="email">&lt;<a class="email" href="mailto:hudson-jaxb-unofficial-guide at hudson.sfbay.sun.com">hudson-jaxb-unofficial-guide at hudson.sfbay.sun.com</a>&gt;</code>.</p><p>The general mode of operation is that:</p><div class="itemizedlist"><ul class="itemizedlist" type="disc"><li class="listitem"><p>When you are answering forum questions, ask yourself if the
            content should instead go to the user's guide. You can then post
            the pointer to the document (trigging a posting by e-mail is handy
            in this case.)</p></li><li class="listitem"><p>It's OK to have TBDs and TODOs. This is an incremental
            effort. Having something is better than not having
            anything.</p></li><li class="listitem"><p>Try not to change section titles, as they are used for
            permalinks.</p></li></ul></div></div></div></div><div class="navfooter"><hr><table width="100%" summary="Navigation footer"><tr><td width="40%" align="left"><a accesskey="p" href="ch02.html">Prev</a>&nbsp;</td><td width="20%" align="center">&nbsp;</td><td width="40%" align="right">&nbsp;<a accesskey="n" href="ch04.html">Next</a></td></tr><tr><td width="40%" align="left" valign="top">Release Notes&nbsp;</td><td width="20%" align="center"><a accesskey="h" href="index.html">Home</a></td><td width="40%" align="right" valign="top">&nbsp;Tools</td></tr></table></div></body></html>